我应该如何以与平台无关的方式获取TimeZoneInfo? [英] How should I fetch TimeZoneInfo in a platform-agnostic way?

查看:466
本文介绍了我应该如何以与平台无关的方式获取TimeZoneInfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆