Search code examples
c#datetime.net-2.0

Get DateTime For Another Time Zone Regardless of Local Time Zone


Regardless of what the user's local time zone is set to, using C# (.NET 2.0) I need to determine the time (DateTime object) in the Eastern time zone.

I know about these methods but there doesn't seem to be an obvious way to get a DateTime object for a different time zone than what the user is in.

 DateTime.Now
 DateTime.UtcNow
 TimeZone.CurrentTimeZone

Of course, the solution needs to be daylight savings time aware.


Solution

  • As everyone else mentioned, .NET 2 doesn't contain any time zone information. The information is stored in the registry, though, and its fairly trivial to write a wrapper class around it:

    SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones
    

    contains sub-keys for all time zones. The TZI field value contains all the transition and bias properties for a time zone, but it's all stuffed in a binary array. The most important bits (bias and daylight), are int32s stored at positions 0 and 8 respectively:

    int bias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 0);
    int daylightBias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 8);
    

    Here's an archive of How to get time zone info (DST) from registry?