.NET handles time zones using two systems: Windows time zones (e.g., "Eastern Standard Time") and IANA time zones (e.g., "America/New_York"). While IANA is the standard for internet APIs, converting between the two is often necessary.
Prior to .NET 6, the windowsZones.xml
file (from the Unicode CLDR project) was the primary method for conversion. However, limitations led to the creation of the TimeZoneConverter
NuGet package, offering a more reliable solution.
Here's how TimeZoneConverter
simplifies the process:
<code class="language-csharp">string tz = TZConvert.IanaToWindows("America/New_York"); // Returns: "Eastern Standard Time" string tz = TZConvert.WindowsToIana("Eastern Standard Time"); // Returns: "America/New_York" string tz = TZConvert.WindowsToIana("Eastern Standard Time", "CA"); // Returns: "America/Toronto"</code>
.NET 6 and later versions provide built-in support for both Windows and IANA time zones on systems with the necessary time zone data and ICU (International Components for Unicode). This simplifies direct conversion:
<code class="language-csharp">TimeZoneInfo windowsZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); TimeZoneInfo ianaZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");</code>
It's important to note that a single Windows time zone might map to several IANA zones. The default is the "golden zone" (CLDR's "001"). To specify a different match, use a country code (as shown in the TimeZoneConverter
example using "CA").
The above is the detailed content of How to Efficiently Translate Between Windows and IANA Time Zones in .NET?. For more information, please follow other related articles on the PHP Chinese website!