在Unity应用程序中引发异常

在Unity应用程序中引发异常

本文介绍了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时区列表.您可能还需要阅读时区标签Wiki 来了解两者之间的区别.

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.

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

08-06 09:03