C# TimeZoneInfo to convert GMT timezone name to system timezone

In windows, we get timezone list like this:

ID    Time zone name               Display string
--    --------------               --------------
0     Dateline Standard Time       (UTC-12:00) International Date Line West
110   UTC-11                       (UTC-11:00) Coordinated Universal Time -11
200   Hawaiian Standard Time       (UTC-10:00) Hawaii
300   Alaskan Standard Time        (UTC-09:00) Alaska

more here.

I use this list to convert from one timezone to another using TimeZoneInfo class which accepts time zone name shown in above list.

Ex.

// Local time zone to UTC
var utcOffset = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero);
var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezoneName); // here tz name can be any name from above table
var localOffset = new DateTimeOffset(date.Value, localTimeZone.GetUtcOffset(utcOffset));
DateTime utcDate = localOffset.UtcDateTime;

Now I came across SalesForce timezone representation like:

Time Zone Code  Time Zone Name
--------------  --------------
GMT+14:00       Line Is. Time (Pacific/Kiritimati)
GMT+13:00       Phoenix Is.Time (Pacific/Enderbury)
GMT+13:00       Tonga Time (Pacific/Tongatapu)
GMT+12:45       Chatham Standard Time (Pacific/Chatham)

more here.

I couldn't find built in functionality to use either time zone code or time zone name given in above table for the conversion.

Jon Skeet
people
quotationmark

If you're happy to stick with TimeZoneInfo and DateTime/DateTimeOffset, you can use Matt Johnson's TimeZoneConverter library to convert the IANA ID (the part in brackets, e.g. Pacific/Kiritimati) to a Windows system time zone ID.

Examples from the project page docs:

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

Or:

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");

However, things to be aware of:

  • There won't always be a complete mapping from IANA IDs to Windows IDs. Some aren't mapped, although the situation is better than it used to be.
  • The Windows time zone data can be different to the IANA data sometimes. (Again, this is getting better.)
  • Time zone data changes over time. If you're storing future date/time values, you might want to store the time zone and local time rather than the UTC instant. (That instant may not map to the same local time in the future.)
  • Some local times can be ambiguous - e.g. if the clocks go back from 2am to 1am on a particular date in a particular time zone, then 1:15am on that day will occur twice in that time zone. Think about how you want to handle that, and test it.

I'd personally recommend using my Noda Time library anyway, as a cleaner way of handling date/time, but I acknowledge that if you've got a lot of code dealing with DateTime already, that may not be feasible.

people

See more on this question at Stackoverflow