TimeZoneInfo - A Small .NET 3.5 Gem

December 7, 2008 at 4:10 PMBen

One new handy class introduced in the .NET 3.5 framework is the TimeZoneInfo class.  This class allows you to get date and time information for any time zone in the world.  Prior to .NET 3.5, the framework exposed methods to get date and time information only for the time zone the server was set at.

I've used this class to find the date/time of a place other than where the server is located.  If you're lucky, the server your website is running on will be in the same timezone you want to save and display dates and times for.  Even if you're in a different timezone, let's say in New York and your server is in California, well you can just add 3 hours to the server time to get New York time.

It isn't always this easy living in Arizona where daylight saving time (DST) is not observed.  In the summer, Arizona is in the same timezone as California (PST) three hours behind the east coast and in the winter, Arizona is in MST two hours behind the east coast.  Your server may be in Arizona but you want a west coast time for your application, or your server may be in California and you want Arizona time for your application.

If the server is in Arizona, and you want to know what time it is in California, you can use the TimeZoneInfo class to find this out.

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime PstDateTime = TimeZoneInfo.ConvertTime(DateTime.Now, tzi);

PstDateTime now contains the current date/time in California.  This code will work year round as daylight saving time and any other adjustment rules are taken into account by the ConvertTime() static function.  So, in the winter, PstDateTime will be one hour earlier than Arizona time and in the summer, PstDateTime will be the same as Arizona time.  This functionality makes life very convenient since you don't need to worry about trying to calculate when DST starts and ends each year.

You may even want to just know if daylight saving time is in effect for any given date/time value.

bool IsDaylightSavingTime = tzi.IsDaylightSavingTime(PstDateTime);

This tells you whether it is daylight saving time for PstDateTime.  Let's check the status of DST for two different dates:

// false
bool IsDaylightSavingTimeAprilFirst2000 = tzi.IsDaylightSavingTime(DateTime.Parse("4/1/2000"));
// true
bool IsDaylightSavingTimeAprilFirst2008 = tzi.IsDaylightSavingTime(DateTime.Parse("4/1/2008"));

There's actually a handful of other static and non-static members of the TimeZoneInfo class available that can come in handy depending on your needs.  Members such as GetUtcOffset(), ConvertTimeToUtc(), DisplayName, etc. provide a wide range of built-in capability.  The list of available time zones you can pass into the FindSystemTimeZoneById method can be found via the GetSystemTimeZones method.

Posted in: Development


Comments are closed