Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve timezone conversion error?

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?

like image 493
ThunD3eR Avatar asked Jan 21 '26 10:01

ThunD3eR


2 Answers

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.

    • You're using the Windows time zone ID "Central European Standard Time", which has a display name of "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb".
    • For Sweden, you should actually use the ID "W. Europe Standard Time", which has a display name of "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna"
    • You can read more about this in the section titled "The Microsoft Windows Time Zone Database" in the timezone tag wiki.
  • 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")
like image 61
Matt Johnson-Pint Avatar answered Jan 22 '26 23:01

Matt Johnson-Pint


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);
like image 33
Tom Avatar answered Jan 23 '26 00:01

Tom