views:

3219

answers:

2

I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time.

I am using .NET 3.5 (thank god) but It's still baffling me.

Thanks

EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for.

+3  A: 

You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information.

TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc).

Update: I think this specifically answers your question:

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);
Console.WriteLine(dto);
Console.ReadLine();

That code creates a DateTime at -8 offset. The default installed time zones are listed on MSDN.

cfeduke
DateTimeOffset, TimeZone, and TimeZoneInfo are value types available in 3.0, sorry that's not exactly clear in my answer.
cfeduke
if you create a new DateTime object, can you set it's Time Zone? That's where my brain is hurting. It's my understanding, which may be incorrect, that TimeZone.CurrentTimeZone returns the time zone info for the local machine, but it can't be set to another zone. Going to MSDN to dig deeper. Thanks
discorax
Yes, you can, I have updated the answer with code where I verified that this works.
cfeduke
"That code creates a DateTime..."should be"That code creates a DateTimeOffset..."Also this solution does not take Daylight Savings time into account.TimeZoneInfo.ConvertTime will check if the time is in the DST range and adjust automatically.
Mike Blandford
+8  A: 

Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide.

// _timeZoneId is the String value found in the System Registry.
// You can look up the list of TimeZones on your system using this:
// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones();
// As long as your _timeZoneId string is in the registry 
// the _now DateTime object will contain
// the current time (adjusted for Daylight Savings Time) for that Time Zone.
string _timeZoneId = "Pacific Standard Time";
DateTime startTime = DateTime.UtcNow;
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);
_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);

This is the code snippit I ended up with. Thanks for the help.

discorax