How to translate between Windows and IANA time zon

2018-12-31 08:16发布

As described in the timezone tag wiki, there are two different styles of time zones.

  • Those provided by Microsoft for use with Windows and the .Net TimeZoneInfo class are identified by a value such as Eastern Standard Time.

  • Those provided by IANA in the TZDB are identified by a value such as America/New_York.

Many Internet-based APIs use the IANA time zones, but for numerous reasons one might need to convert this to a Windows time zone id, or vice-versa.

How can this be accomplished in .Net?

1条回答
美炸的是我
2楼-- · 2018-12-31 08:30

The primary source of the data for conversion between Windows and IANA time zone identifiers is the windowsZones.xml file, distributed as part of the Unicode CLDR project.

However, CLDR is released only twice annually. This, along with the periodic cadence of Windows updates, and the irregular updates of the IANA time zone database, makes it complicated to just use the CLDR data directly. Keep in mind that time zone changes themselves are made at the whim of the world's various governments, and not all changes are made with sufficient notice to make it into these release cycles before their respective effective dates.

There are a few other edge cases that need to be handled that are not covered strictly by the CLDR, and new ones pop up from time to time. Therefore, I've encapsulated the complexity of the solution into the TimeZoneConverter micro-library, which can be installed from Nuget.

Using this library is simple. Here are some examples of conversion:

string tz = TZConvert.IanaToWindows("America/New_York");
// Result:  "Eastern Standard Time"

string tz = TZConvert.WindowsToIana("Eastern Standard Time");
// result:  "America/New_York"

string tz = TZConvert.WindowsToIana("Eastern Standard Time", "CA");
// result:  "America/Toronto"

There are more examples on the project site.

It's important to recognize that while an IANA time zone can be mapped to a single Windows time zone, the reverse is not true. A single Windows time zone might be mapped to more than one IANA time zone. This can be seen in the above examples, where Eastern Standard Time is mapped to both America/New_York, and to America/Toronto. TimeZoneConverter will deliver the one that CLDR marks with "001", known as the "golden zone", unless you specifically provide a country code and there's a match for a different zone in that country.

Note: This answer has evolved over the years, so comments below may or may not apply to the current revision. Review the edit history for details. Thanks.

查看更多
登录 后发表回答