Home > Blockchain >  How to get IANA timezone in C# without conversion
How to get IANA timezone in C# without conversion

Time:06-23

When you run .net on windows machines, it pulls the timezone info from the Windows registry and thus uses Windows timezone ids rather than IANA. You can convert between them, but consider the following code:

TimeZoneInfo.TryConvertIanaIdToWindowsId("Canada/Eastern", out string temp2);
TimeZoneInfo.TryConvertWindowsIdToIanaId(temp2, out string temp3);
Debug.WriteLine(temp2 ?? "NULL"); //Eastern Standard Time
Debug.WriteLine(temp3 ?? "NULL"); //America/New_York

Converting from Windows timezones to IANA timezones is not two way. There seems to be a canonical timezone that windows' cluster timezones get changed to (in this case New York).

This isn't a problem on non-windows machines since they all use IANA but, for windows, I cannot get the true IANA timezone of the user. Is there anyway around this?

How does windows even get away with doing this if the timezones it groups together (like 'America/New_York' and 'Canada/Eastern' into 'Eastern Standard Time') may eventually (or already) have different historical daylight savings rules and whatnot? That said, even if they were the same in all but name, I'd like to get the proper IANA timezone of the machine somehow.

CodePudding user response:

The method TimeZoneInfo.TryConvertWindowsIdToIanaId has an overload where you can specify the region:

TimeZoneInfo.TryConvertWindowsIdToIanaId(string windowsId, string? region, out string ianaId);

With the region parameter you can specify a country/region as ISO 3166 code.

You can get the country/region code with RegionInfo.CurrentRegion.TwoLetterISORegionName

  • Related