TimeZoneInfo in .NET Core when hosting on unix (ng

2019-04-20 23:44发布

For example, when I try to do the following.

TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")

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

4条回答
Rolldiameter
2楼-- · 2019-04-21 00:13

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

查看更多
祖国的老花朵
3楼-- · 2019-04-21 00:14

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");
查看更多
欢心
4楼-- · 2019-04-21 00:17

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

查看更多
一纸荒年 Trace。
5楼-- · 2019-04-21 00:20

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.");
}
查看更多
登录 后发表回答