Pages

Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Monday, 1 December 2008

Get time in HH:mm format regardless of the local culture

DateTime.Now.ToShortTimeString() returns a string that depends on the culture. DateTime.Now.ToString("HH:mm") is deterministic. Use DateTime.Now.ToUniversalTime.ToString("HH:mm") to get the current HH:mm time in UTC.

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: