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.
In .NET 3.5, there is TimeZoneInfo
, which provides a lot of functionality in this area; 2.0SP1 has DateTimeOffset
, but this is much more limited.
Getting UtcNow
and adding a fixed offset is part of the job, but isn't DST-aware.
So in 3.5 I think you can do something like:
DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(
DateTime.UtcNow, "Eastern Standard Time");
But this simply doesn't exist in 2.0; sorry.
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?