【问题标题】:How should I fetch TimeZoneInfo in a platform-agnostic way?我应该如何以与平台无关的方式获取 TimeZoneInfo?
【发布时间】:2017-12-16 17:10:54
【问题描述】:

我正在将 .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?

【问题讨论】:

    标签: macos timezone .net-core


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      • 2011-12-13
      • 2011-10-03
      • 2012-02-23
      • 1970-01-01
      相关资源
      最近更新 更多