I'm working on an application that needs to run 24H a day, and am working on correctly implementing support for DST. All times are currently stored in UTC, but I'm having issues when I try to display in local time. Right now I'm using savedDate.ToLocalTime()
to convert from DB values to local time for display. This seems to be working fine, except for when I change the time zone information in an effort to test DST. If I modify the timezone on the client pc, the display doesn't update with the new time zone. Is there a better way to test DST, or is my conversion to local time incorrect for this scenario?
views:
225answers:
3I remember reading, perhaps regarding the Compact Framework, about .NET not being the most reliable when it comes to reporting about DST. More reliable was getting the current time in local time and UTC, and then determining (and using in future adjustments) the difference yourself. That seems like a horrible route to go if it's not really necessary. I'll see if I can find a reference backing up what I think I remember.
What are you doing, exactly, to change the timezone on the workstation?
Hmm. Do you expect to actually have to change time zone while the app is running? I wouldn't be surprised if the framework cached it after it's first fetched.
I would set the time zone on the device, change the time to "just before the change to DST", run the app and check that it's reporting times correctly. Then change the time to "just before the change out of DST".
Bear in mind that depending on your device and the age of its time zone database, it may not know about the change to DST in the US a few years ago. (Ah, time zones. Gotta love 'em.)
If you retrieve a DateTime value from a database, you will generally get a DateTime with the Kind property set to DateTimeKind.Unspecified. Basically because any database-specific DateTime types I'm aware of (e.g. SqlDateTime) don't include timezone information.
If you then try to "convert" this to local time using savedDate.ToLocalTime(), you'll get back the same DateTime value that was stored, without any conversion.
What you need to do is indicate that the saved date is in UTC before performing the conversion, something like:
DateTime savedDateTime = (DateTime) reader["SomeDateTimeColumn"];
// Convert from unspecified to UTC
DateTime utcDateTime = savedDateTime.SpecifyKind(savedDateTime, DateTimeKind.Utc);
...
// Convert from UTC to local
DateTime localDateTime = utcDateTime.ToLocalTime();