我应该如何以与平台无关的方式获取 TimeZoneInfo? [英] How should I fetch TimeZoneInfo in a platform-agnostic way?
问题描述
我正致力于将 .NET Framework 4.5 应用程序移植到 .NET Core 2.0,并已开始在我的 Mac 上进行一些测试.当我在 Windows 上的 .NET Core 2.0 上运行此代码时,它工作正常:
I'm working on porting a .NET Framework 4.5 app to .NET Core 2.0 and have started to do some testing on my Mac. When I run this code on .NET Core 2.0 on Windows it works fine:
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
但它在 Mac 上抛出以下异常:
but it throws the following exception on the 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 上的问题.
After some poking around, it seems that using the time zone ID "America/Los_Angeles"
fixes the problem on the Mac.
我想知道我应该怎么做才能使这个平台不可知.我应该尝试查找 "Pacific Standard Time"
,然后尝试在 catch 块中查找 "America/Los Angeles"
吗?这看起来很笨拙,如果另一个平台还有另一个字符串呢?有没有更好的方法来查找我想要的 TimeZoneInfo?
I'm wondering what I should do to keep this platform agnostic. Should I try to find "Pacific Standard Time"
, and then try to find "America/Los Angeles"
in a catch block? That seems clumsy, and what if another platform has yet another string for it? Is there a better way to look up the TimeZoneInfo I want?
推荐答案
这是一个已知问题,在 dotnet/corefx#11897.目前还没有内置的解决方案.
This is a known problem, and is tracked in dotnet/corefx#11897. There's no built-in solution yet.
但是,我的 TimeZoneConverter 库可用于此目的.
However, my TimeZoneConverter library can be used for this.
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Pacific Standard Time");
它的工作原理是首先查看计算机上是否存在时区.如果不是,那么它会转换为 IANA 格式的等效时区(在本例中为 America/Los_Angeles
),并尝试用它来检索它.相反的情况也适用,因此您可以在任何操作系统上使用任一格式.
It works by first seeing if the time zone is present on the computer. If not, then it converts to the equivalent time zone in IANA format (America/Los_Angeles
in this case), and trying to retrieve it with that instead. The opposite case also works, so you can use either format on any OS.
这篇关于我应该如何以与平台无关的方式获取 TimeZoneInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!