
.NET 3.5+Get Time Zone Information (2)
When creating applications that will be used internationally, particularly with a shared database that holds date and time data, it is important to be able to obtain information about time zones. This can be achieved with .NET 3.5's TimeZoneInfo class.
Retrieving UTC Time Zone Information
When storing date and time information in an international application, UTC times are very important. One common strategy is to store all times using UTC and only converting to a local time for display purposes or reporting. This reduces the problems of comparing times in different time zones and the risk of ambiguous times that occur near the transition periods between standard and daylight saving time.
The TimeZoneInfo class includes a static property that represents a special UTC time zone. This time zone does not support daylight saving time, so has no ambiguous times, and always has an offset of zero. To access the UTC time zone information, use the static Utc property:
Console.WriteLine("ID\t{0}", TimeZoneInfo.Utc.Id);
Console.WriteLine("Name\t{0}", TimeZoneInfo.Utc.DisplayName);
Console.WriteLine("S. Name\t{0}", TimeZoneInfo.Utc.StandardName);
Console.WriteLine("D. Name\t{0}", TimeZoneInfo.Utc.DaylightName);
Console.WriteLine("Offset\t{0}", TimeZoneInfo.Utc.BaseUtcOffset);
Console.WriteLine("DST?\t{0}", TimeZoneInfo.Utc.SupportsDaylightSavingTime);
/* OUTPUT
ID UTC
Name UTC
S. Name UTC
D. Name UTC
Offset 00:00:00
DST? False
*/
Retrieving a Specific Time Zone
If you wish to obtain information about a time zone that is neither the local time zone nor UTC, you can access it using the FindSystemTimeZoneById method, passing the ID of the desired time zone as the only parameter. This method is also useful if you wish to retrieve the local time zone of the user but ignore any changes they may have made to the daylight saving time setting.
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
Retrieving a List of Valid Time Zones
In some situations you will wish to obtain the complete list of time zones that are known by the local system. This can be achieved by calling the GetSystemTimeZones method. The method returns a ReadOnlyCollection of TimeZoneInfo objects. To output all known time zones using a foreach loop, execute the code below:
ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo zone in zones)
{
Console.WriteLine("{0}", zone.Id);
}
Time Zone Adjustment Rules
Time zones can include rules that cause the local clock to be adjusted periodically for daylight saving time. The rules for the dates and times for such changes vary around the world and can be different for countries that are within the same geographical time zone. The TimeZoneInfo class can be used to obtain information about these time changes using instances of the nested class, "TimeZoneInfo.AdjustmentRule".
12 October 2009