Recently, I ran into a small issue with timezones. On my local system, I was able to get the timezone but as soon I deployed, I started getting an error.
Unfortunately, Windows and Linux use different timezone systems
- On Windows, they are identified by a value provided by Microsoft and takes a form such as “New Zealand Standard Time”.
- On Linux/OSX, they are identified by a value provided by IANA in the TZDB and takes a form such as “Pacific/Auckland”.
This makes it a little tricky to get the TimeZoneInfo, especially, if you want to make sure the code works regardless of the system it is running on.
The easiest way I have found to solve this is to check if the Windows value exists in the list of time zones. If it exists, use the Windows value to get the time zone info, else use the IANA value.
var nzTimeZone = TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "New Zealand Standard Time") ? TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time") : TimeZoneInfo.FindSystemTimeZoneById("Pacific/Auckland");