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

For example, when I try to do the following.

TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")

I get an error that is TimeZonenot available on the local computer. When I run it locally, it works, but there I run it on windows. When deployed, it runs on a Unix machine in Nginx. I see that I am FindSystemTimeZoneByIdlooking for the wrong folder when it comes to Unix. Is there any way to make this work?

+18
source share
5 answers

.Net Core uses the system time zone. Unfortunately, Windows and Linux have different time zone systems. You now have two ways:

+16

?

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

IANA https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

+10

Windows, IANA, Windows :

var tzi  = TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Eastern Standard Time") ? 
    TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") : 
    TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
+4

, try/catch, , :

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.");
}
+4

I managed 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 this may help in some scenarios.

+1
source

Source: https://habr.com/ru/post/1666358/


All Articles