Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c# - How does DateTimeOffset deal with daylight saving time?

I am storing schedules in the database as a day of the week, hour and minute. When the data is read we create a DateTime object for the next occurrence of that day, hour and minute, but I need to modify this to be DST-aware. I am able to modify the database if necessary.

I know that DateTimeOffset stores a UTC date/time and an offset. I also know from this MSDN blog entry that DateTimeOffset should be used to "Work with daylight saving times".

What I'm struggling to understand is exactly how DateTimeOffset "work(s) with daylight saving times". My understanding, little that there is, is that daylight saving times are a political decision and cannot be inferred from purely an offset. How can it be that this structure is DST friendly if it only stores an offset and not a named timezone or country?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DateTimeOffset itself isn't really DST-aware, but TimeZoneInfo is. A DateTimeOffset represents a fixed instant in time - so you get to a DateTimeOffset via something that is time zone aware. In other words, if I asked for a DateTimeOffset now in the UK, I'd end up with something with an offset of +1 hour from UTC. If I asked for a DateTimeOffset for some time in December in the UK, I'd end up with something with an offset of 0 hours from UTC.

If you change your database to include the offset and you create the DateTimeOffset from the user's chosen DateTime (which should be of kind "unspecified") and their time zone, then that should give you the correct offset taking DST into account.

One thing to be aware of though: if I schedule something now for "2 years time" and you determine the offset now, that offset may not be correct in the future - for example, the government could change when DST applies, and obviously that's not going to change what's stored in your database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...