TimeZoneInfo in .NET Core when hosting on unix (nginx)

后端 未结 5 731
半阙折子戏
半阙折子戏 2020-12-09 07:55

For example, when I try to do the following.

TimeZoneInfo.FindSystemTimeZoneById(\"Central European Standard Time\")

I get the error, that

相关标签:
5条回答
  • 2020-12-09 08:05

    .Net Core using system timezone. Unfortunately Windows and Linux have different timezone system. Now you have two ways:

    • Use other (and universal) impementation of timezone like Noda time
    • Translate between Windows and IANA time zones, e.g. using the TimeZoneConverter micro-library.
    0 讨论(0)
  • 2020-12-09 08:06

    If you want to try a Windows time zone and then fallback on a IANA one if the Windows one doesn't exist:

    var tzi  = TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Eastern Standard Time") ? 
        TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") : 
        TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
    
    0 讨论(0)
  • 2020-12-09 08:08

    I was able to support this use-case in my development docker image by doing the following:

    cp /usr/share/zoneinfo/America/Los_Angeles "/usr/share/zoneinfo/Pacific Standard Time"
    

    Obviously, I don't think that would be a good idea for production deployments. But it might help in some scenarios.

    0 讨论(0)
  • 2020-12-09 08:15

    Working of off the previous answer, we can avoid the expensive try/catch by checking which OS we're running on:

    using System;
    using System.Runtime.InteropServices;
    
    TimeZoneInfo easternStandardTime;
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
      easternStandardTime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    }
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    {
      easternStandardTime = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
    }
    if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
    {
      throw new NotImplementedException("I don't know how to do a lookup on a Mac.");
    }
    
    0 讨论(0)
  • 2020-12-09 08:17

    Can you please try this?

       TimeZoneInfo easternZone;
            try
            {
                easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            }
            catch (TimeZoneNotFoundException)
            {
                easternZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
            }
    

    You can review the list of IANA time zones here https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

    0 讨论(0)
提交回复
热议问题