Pages

Monday 13 October 2008

Timezone conversion

How to convert a local time from a given time zone into UTC?
For instance how to convert the time in New York (Time zone: Eastern Standard Time) into UTC time, taking into account the fact that daylight saving is currently active in New York (until November 2)? Sounds trivial? Well it's not, at least not until .NET Framework 3.5.
The standard time zones are listed in the Windows registry: each time zone string is a key. The values under that key describe the timezone. For instance the "Eastern Standard Time" key contains info such as UTC offset and daylight saving start/end dates. Unless you use 3.5, you have to write code yourself to retrieve that info from the registry. It looks like the simplest way to do it is to use System.TimeZoneInfo in .NET 3.5. Example:
DateTime time = new DateTime(2008, 11, 7, 11, 46, 0, 0); TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); DateTime utcTime = TimeZoneInfo.ConvertTimeFromUtc(time, info); Console.WriteLine("New york time: " + time.ToString()); Console.WriteLine("UTC time : " + utcTime.ToString());
Some resources: