Monday, May 11, 2009

The correct way to convert DateTime between TimeZones

Nope, its not to do it yourself. Instead use the platforms in-built functionality. In .Net (C#), this involves using the TimeZoneInfo object.

Here is an example:

DateTime oldTime = DateTime.ParseExact("05-11-2009 00:01", "MM-dd-yyyy HH:mm", null);
TimeZoneInfo timeZoneSrc = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
TimeZoneInfo timeZoneDst = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
DateTime newTime = TimeZoneInfo.ConvertTime(oldTime, timeZoneSrc, timeZoneDst);
DateTime expectedTime = DateTime.ParseExact("05-10-2009 23:01","MM-dd-yyyy HH:mm", null);
Debug.Assert(newTime == expectedTime, "Failed");

To get a list of supported time zone IDs, look under the registry key “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones

Here is a sample list:

  • Eastern Standard Time
  • Central Standard Time
  • Mountain Standard Time
  • Pacific Standard Time
  • Indian Standard Time

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.