Search code examples
c#.nettimezoneasp.net-core-webapi

Exception calling TimeZoneInfo.FindSystemTimeZoneById()


Why does the following line succeed in a .NET Console application, but fails in an ASP.NET Core WebApi application?

TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin")

The exception in the WebAPI case is:

Unhandled exception. System.TimeZoneNotFoundException: The time zone ID 'Europe/Berlin' was not found on the local computer.
   at System.TimeZoneInfo.FindSystemTimeZoneById(String id)
   at Program.<Main>$(String[] args) in C:\Development\TimezoneTest\WebAPI\Program.cs:line 1

Both projects are part of the same solution, one created using the console template, the other using the webapi template. I run both of them in the IDE or using dotnet run.

I am aware of how to solve the problem. I'm interested in what the cause for the difference is, that results in an Exception in one case but doesn't in the other.


I'm also aware of a similar question and the accepted answer contains a hint about registry information, but I don't fully understand it, given that I'm running both apps locally on the same Windows laptop.


Solution

  • After deleting W. Europe Standard Time in my registry table, I can reproduce the issue.

    enter image description here

    Test Steps

    Try to check W. Europe Standard Time is exist in your computer or not.

    Path

    Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
    

    enter image description here

    Solution

    Create a timezone.reg file and excute it, then verify it in Registry Table.

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\W. Europe Standard Time]
    "Display"="(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna"
    "Dlt"="W. Europe Daylight Time"
    "MUI_Display"="@tzres.dll,-320"
    "MUI_Dlt"="@tzres.dll,-321"
    "MUI_Std"="@tzres.dll,-322"
    "Std"="W. Europe Standard Time"
    "TZI"=hex:c4,ff,ff,ff,00,00,00,00,c4,ff,ff,ff,00,00,0a,00,00,00,05,00,03,00,00,\
      00,00,00,00,00,00,00,03,00,00,00,05,00,02,00,00,00,00,00,00,00
    

    Double-click it and select yes.

    enter image description here

    enter image description here

    Verify it.

    enter image description here

    Then restart your webapi project in vs2022.

    enter image description here

    Workaround

    We also can use time zone ID W. Europe Standard Time to replace 'Europe/Berlin'.

    var aa = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
    var ab = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");