开发者

DateTimeOffset display after daylight savings change

开发者 https://www.devze.com 2023-03-21 16:08 出处:网络
I have a question about DateTimeOffset and daylight savings time.To explain my question lets assume that right now the date and time is:

I have a question about DateTimeOffset and daylight savings time. To explain my question lets assume that right now the date and time is:

11/6/2010  10:15:00 AM 

If I run this code:

DateTimeOffset myTime = DateTimeOffset.Now;
Console.WriteLine("Local time: " + myTime.ToLocalTime().DateTime);

Then I get this result:

Local time: 11/6/2010 10:15:00 AM

Meaning that the event happened at 10:15 in the morning (my time zone is Mountain Daylight Time (-6 offset)).

So, then I save this DateTimeOffset to my SQL Server 2008 db (as a DateTimeOffset). The next day I want to display it to the user. But now daylight savings has expired.

If I run the above WriteLine with the saved off value (from the previous day) what will display?

The offset stored in the database is -6. But now that daylight savings is over, the current offset is -7. So as I understand the documentation, it will first convert my time to UTC time (so it takes 10:15 AM and adds 6 hours (4:15 pm). It will then subtract the current offset of the local time (4:15 pm - 7 = 9:15 AM).

So if I my math is right, now when I display my event, it will show that it occurred at 9:15 AM rather than 10:15 AM.

This is not good. I want to store time zone information, but I need my times to stay static in the same time zone. (Meaning th开发者_开发知识库at if the event happened at 10:15 AM in Utah, then the next time I look at it (in Utah), I need to see that it was at 10:15 AM, regardless if the daylight savings time change has happened.

I can't think I am the first one to have this issue. What do others do to fix this? (Or do I have the facts wrong?)


No, it won't add the current offset - it'll add the offset at that date which is still -6. So it should still display 10:15AM, because it knows the date involved, and thus the time zone rules in force on that date.

You may well want to store a simple UTC time and the time zone identifier separately, by the way. If you're storing a time zone, then using DateTimeOffset won't be particularly helpful over just a UTC date/time. (On the other hand, it's clearer that it does represent an instant in time - DateTime is a horribly confused type which doesn't let you easily express what you're trying to represent.)

Of course I'd personally encourage you to look at Noda Time which in my very biased opinion is a rather clearer date/time API than the built-in one... but which isn't quite ready for production use. (We're getting there though...)

0

精彩评论

暂无评论...
验证码 换一张
取 消