I am trying to convert to a swedish timezone with this code:
Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime currentDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
var swedishTime = TimeZoneInfo.ConvertTime(currentDate, cet, TimeZoneInfo.Local);
For some reason I am getting:
{"The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.\r\nParameter name: sourceTimeZone"}
What am i missing?
A few things:
Culture only affects output formatting when converting to/from strings. It doesn't affect time zone conversions, so it is unnecessary here.
The time zone identifiers used by TimeZoneInfo on Windows come from the Windows operating system itself, and sometimes their names do not match up to what you may expect.
"Central European Standard Time", which has a display name of "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb"."W. Europe Standard Time", which has a display name of "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna"Since it appears you are looking for the current time in a particular time zone, you should not be going through the local time zone at all. Just convert directly from UTC to the target time zone.
The code should simply be:
var tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
var swedishTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz);
Or if you prefer, you can use a convenience method:
var swedishTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow,
"W. Europe Standard Time")
Just delete "TimeZoneInfo.Local" from "var swedishTime".
Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime currentDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
var swedishTime = TimeZoneInfo.ConvertTime(currentDate, cet);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With