uncategorized

.Net vNext (Orcas) and TimeZone2

One of the new features in C# 3.0 (more appropriately .NET 3.5) is the addition of the TimeZone2 object.  TimeZone2 greatly enhances your ability to work with different time zones over the older implementation, TimeZone. You can see the enhanced interface provided by TimeZone2 (on the right) over TimeZone (on the left).

TimeZone TimeZone2

The the biggest change that I noticed right away is the introduction of a list of system time zones.  You can access and iterate the list as simply as:

1
2
3
foreach (TimeZone2 timeZone in TimeZone2.GetSystemTimeZones()) {
Console.WriteLine(timeZone.Id.ToString() + "(" + timeZone.BaseUtcOffset.ToString() + ")");
}

Which will output:

TimeZone2Output

Another big difference is the replacement of the CurrentTimeZone property with the Local property.  With the change in property name also comes a change in return type.  TimeZone2.Local will return you a TimeZone2 object with all the goodness that the new class provides.

The last feature that I liked was the ConvertTime method.  It allows you to provide a DateTime object for conversion and tell it what time zone to convert it to.  If you’re working with a database that stores time information in Greenwich Mean Time (+/- 0 hrs) and then working a bunch of code to display it to your user in their local time zone, your job has just gotten easier.  What you can do now is this:

1
Console.WriteLine("Converted Time: " + TimeZone2.ConvertTime(someDateTimeFromDatabase, TimeZone2.Local)); 

This is a trivial example that of course wouldn’t work on a web or application server, but to do that all you’d have to do is provide the client’s time zone as a TimeZone2 object and use it as the second parameter.