我应该如何以平台无关的方式获取TimeZoneInfo?

Rik*_*son 5 macos timezone .net-core

我正在努力将.NET Framework 4.5应用程序移植到.NET Core 2.0,并开始在我的Mac上进行一些测试.当我在Windows上的.NET Core 2.0上运行此代码时,它工作正常:

TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
Run Code Online (Sandbox Code Playgroud)

但它在Mac上抛出以下异常:

System.TimeZoneNotFoundException: The time zone ID 'Pacific Standard Time' was not found on the local computer. ---> System.IO.FileNotFoundException: Could not find file '/usr/share/zoneinfo/Pacific Standard Time'.
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.File.ReadAllBytes(String path)
   at System.TimeZoneInfo.TryGetTimeZoneFromLocalMachine(String id, TimeZoneInfo& value, Exception& e)
   --- End of inner exception stack trace ---
   at System.TimeZoneInfo.FindSystemTimeZoneById(String id)
Run Code Online (Sandbox Code Playgroud)

经过一番探索后,似乎使用时区ID "America/Los_Angeles"修复了Mac上的问题.

我想知道我应该做些什么来保持这个平台不可知.我应该尝试找到"Pacific Standard Time",然后尝试"America/Los Angeles"在catch块中查找?这看起来很笨拙,如果另一个平台还有另一个字符串呢?有没有更好的方法来查找我想要的TimeZoneInfo?

Mat*_*int 9

这是一个已知问题,并在dotnet/corefx#11897中进行跟踪.还没有内置的解决方案.

但是,我的TimeZoneConverter库可以用于此目的.

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Pacific Standard Time");
Run Code Online (Sandbox Code Playgroud)

它的工作原理是首先查看计算机上是否存在时区.如果没有,那么它将转换为IANA格式的等效时区(America/Los_Angeles在本例中),并尝试使用它来检索它.相反的情况也适用,因此您可以在任何操作系统上使用任一格式.