Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c# - TimeZoneInfo.FindSystemTimeZoneById() throws exception in a Unity application

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

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

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
  ...

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

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.

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

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...