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

时间:2017-12-16 17:10:54

标签: macos timezone .net-core

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

TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");

但它在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)

经过一番探索之后,似乎使用时区ID "America/Los_Angeles"解决了Mac上的问题。

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

1 个答案:

答案 0 :(得分:6)

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

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

TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Pacific Standard Time");

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