简体   繁体   中英

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?

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);

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")

I faced the same issue and I fixed it by changing to DateTimeKind.Unspecified .

Instead of this

var currentDateTime = DateTime.UtcNow;

I put this:

var currentDateTime = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Unspecified);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM