2

I am trying to get TimeZoneInfo using C#.

I tried using TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles"); but that fails with the following error

System.TimeZoneNotFoundException: 'The time zone ID 'America/Los_Angeles' was not found on the local computer.'

How to correctly find TimeZoneInfo for America/Los_Angeles using C#?

Jay
  • 1,168
  • 13
  • 41

2 Answers2

6

I would recommend using TimeZoneConverter package to get the timezone-info.

PM> Install-Package TimeZoneConverter

Then you can get the TimeZoneInfo using any of the following

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Pacific Standard");
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/Los_Angeles");
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Mike A.
  • 121
  • 3
  • This worked! Never experienced this issue before Asp.Net 6. Running locally, there wasn't an issue. In Azure, with Asp.net 6 selected in the Configuration - General settings section, this was still a problem. – Dumber_Texan2 Mar 31 '23 at 17:33
0

TimeZoneInfo.FindSystemTimeZoneById takes in an ID found within the registry of Windows (specifically, HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone), thus it must be one that exists on the machine. Los Angeles is in the "Pacific Standard Time" zone.

Thus, to calculate the current Los Angeles time, you would need to first get the TimeZoneInfo for the "Pacific Standard Time" zone, and then you can get the current UTC time and Add the TimeZoneInfo's BaseUtcOffset to it to calculate the time in Los Angeles.

TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime laTime = DateTime.UtcNow.Add(timeZoneInfo.BaseUtcOffset); 
Timothy G.
  • 6,335
  • 7
  • 30
  • 46
  • I am using a CMS that return the timezone id as `America/Los_Angeles` not as `Pacific Standard Time`. I want to be able to use the id provided by the CMS and get the TimeZoneInfo. Is there a way to convert `America/Los_Angeles` to `Pacific Standard Time`? – Jay Feb 21 '21 at 21:55
  • @Jay You can maintain some sort of code structure within your project that translates the CMS values to the ID's you **must** use if you want to use that `TimeZoneInfo` method. You can't simply use the CMS values, or you will throw that TimeZoneNotFoundException (unless the CMS value coincidentally corresponds to the IDs in the registry). Maintaining something like that can be a bear, unless you only work with a handful of timezones. – Timothy G. Feb 21 '21 at 21:58