Reputation: 402
I receive a strange result when I try to find a time zone for "GMT Standard Time":
It returns UTC +00:00 when I expect to receive +01:00.
The next weird thing is when I convert UTC time to "GMT", then 1 hour is added to the time.
This is an example of the code:
var gmtTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var timeUtc = DateTime.UtcNow;
var gmtTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, gmtTimeZone);
Am I doing something wrong? How to get the correct display name? I need to allow the user to select a timezone and it's important to show the correct name.
Upvotes: 0
Views: 882
Reputation: 9209
The issue is that this is a TimeZoneInfo conversion.
From .NET 6.0 TimeZoneInfo.ConvertTimeFromUtc description
When performing the conversion, the ConvertTimeFromUtc method applies any adjustment rules in effect in the destinationTimeZone time zone.
Thus as, at the time of posting, GMT Standard Time as used by the United Kingdom is adjusted by the Daylight saving time of 1 hour.
Windows Default Time Zones shows that "GMT Standard Time" applies to the United Kingdom only.
This can be verified as follows:
var gmtTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var timeUtc = DateTime.UtcNow;
var gmtTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, gmtTimeZone);
var daylightSaving = gmtTime.IsDaylightSavingTime() ? "Yes" : "No";
Console.WriteLine($"UTC time : {timeUtc}");
Console.WriteLine($"GMT timezone time : {gmtTime}");
Console.WriteLine($"GMT timezone daylight saving? : { daylightSaving}");
gives:
UTC time : 18/08/2022 10:27:32
GMT timezone time : 18/08/2022 11:27:32
GMT timezone daylight saving? : Yes
If you wish to just use local time (as set on the user's system) then you can just use DateTime.ToLocalTime()
e.g.
Console.WriteLine($"utc from gmtTime : {utc}");
Console.WriteLine($"utc to local : {utc.ToLocalTime()}");
gives:
utc from gmtTime : 18/08/2022 10:38:36
utc to local : 18/08/2022 11:38:36
To remove ambiguities when selecting a time zone I would recommend that you use the ISO3166 code e.g. "GB" instead of "GMT Standard Time".
Upvotes: 1