Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...