Runtime: System.TimeZoneInfo.ConvertTimeFromUtc bug

Created on 3 Oct 2018  路  3Comments  路  Source: dotnet/runtime

We want to convert time.

Example
Localhost
DateTimeOffset TimeZoneInfoConvert = System.TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse("10/9/2018 8:00:00 AM"), System.TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));

Correct result: 10/9/2018 10:00:00 AM +02:00

Server
DateTimeOffset TimeZoneInfoConvert = System.TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse("10/9/2018 8:00:00 AM"), System.TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));

Wrong result: 10/9/2018 10:00:00 AM +00:00

area-System.Runtime bug

Most helpful comment

ConvertTimeFromUtc returns a DateTime rather than a DateTimeOffset. Given no DateTimeStyles, the parse result will have a kind of Unspecified. The implicit conversion to a DateTimeOffset from a DateTime of kind Local or Unspecified uses your local time zone offset. It seems that your server's time zone is UTC while your local machine's time zone is W. Europe Standard Time. You could confirm that by examining TimeZoneInfo.Local.BaseUtcOffset on both systems.

All 3 comments

ConvertTimeFromUtc returns a DateTime rather than a DateTimeOffset. Given no DateTimeStyles, the parse result will have a kind of Unspecified. The implicit conversion to a DateTimeOffset from a DateTime of kind Local or Unspecified uses your local time zone offset. It seems that your server's time zone is UTC while your local machine's time zone is W. Europe Standard Time. You could confirm that by examining TimeZoneInfo.Local.BaseUtcOffset on both systems.

To be clear, almost certainly what you want to be doing is something similar to:

// Because that date format is culture specific!
var parsedUtc = DateTimeOffset.Parse("2018-10-09 08:00:00", CultureInfo.InvariantCulture);
DateTimeOffset TimeZoneInfoConvert = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(parsedUtc, "W. Europe Standard Time");

...or you can use NodaTime, and use the appropriate domain types.

both @sixlettervariables and @Clockwork-Muse are correct. using the way that @Clockwork-Muse suggested will remove the confusion and be explicit.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jkotas picture jkotas  路  3Comments

jzabroski picture jzabroski  路  3Comments

aggieben picture aggieben  路  3Comments

chunseoklee picture chunseoklee  路  3Comments

Timovzl picture Timovzl  路  3Comments