TimeZoneInfo.FindSystemTimeZoneById() 在 Unity 应用程序中引发异常 [英] TimeZoneInfo.FindSystemTimeZoneById() throws exception in a Unity application

查看:41
本文介绍了TimeZoneInfo.FindSystemTimeZoneById() 在 Unity 应用程序中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 C# 控制台应用程序中执行此代码,它工作正常.

If I execute this code in a C# console application, it works fine.

TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
Console.WriteLine(easternZone.DisplayName);

但是,当我在 Unity 应用程序中使用相同的方法时,抛出异常:

However, when I use the same method in a Unity application, an exception is thrown:

System.TimeZoneNotFoundException: Exception of type 'System.TimeZoneNotFoundException' was thrown.
  at System.TimeZoneInfo.FindSystemTimeZoneByFileName (System.String id, System.String filepath) [0x00000] in <filename unknown>:0
  at System.TimeZoneInfo.FindSystemTimeZoneById (System.String id) [0x00000] in <filename unknown>:0
  ...

我注意到的一件奇怪的事情是,当 MSDN 文档明确指出从注册表中检索信息时,会在名为FindSystemTimeZoneByFileName"的方法中引发异常.

A curious thing that I've noticed is that the exception is thrown in a method named "FindSystemTimeZoneByFileName" when the MSDN documentation explicitly says that the information is retrieved from the Registry.

推荐答案

Unity 应用程序使用 Mono,并且可以针对非 Windows 系统 - 因此注册表信息并不总是可用.看来 Mono 将使用系统上可用的任何时区信息,无论是 Windows 时区还是 IANA 时区 - 因此,您可能需要检查其中一个或两者:

Unity applications use Mono, and can target non-Windows systems - so the registry information is not always available. It appears that Mono will use whatever time zone information is available on the system, whether that happens to be Windows time zones, or IANA time zones - so, you may need to check for one or the other, or both:

TimeZoneInfo easternZone;

try
{
    easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
}
catch (TimeZoneNotFoundException)
{
    easternZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
}

当然,如果您通常要在非 Windows 平台上运行,则可以颠倒这些.如果两者都没有找到,那么它仍然会抛出异常.

Of course, you can reverse these if you typically are going to be running on non-Windows platforms. If neither are found, then it will still throw an exception.

您可以此处查看 IANA 时区列表.您可能还想阅读时区标签维基以了解区别.

You can review the list of IANA time zones here. You may also want to read the timezone tag wiki to understand the distinction.

更新:正如 Shaul 的回答指出的那样,您现在可以使用我的 TimeZoneConverter 库来完成此操作.虽然不再需要上述代码,但您现在可以简单地执行此操作:

Update: As Shaul's answer pointed out, you can now use my TimeZoneConverter library to accomplish this. While the above code is no longer required, you can now simply do this instead:

TimeZoneInfo easternZone = TZConvert.GetTimeZoneInfo(timeZoneName);

timeZoneName 参数可以是 America/New_YorkEastern Standard Time.

The timeZoneName parameter can be either America/New_York or Eastern Standard Time.

这篇关于TimeZoneInfo.FindSystemTimeZoneById() 在 Unity 应用程序中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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