DateTime vs DateTimeOffset

2018-12-31 04:18发布

Currently, we have a standard way of dealing with .net DateTimes in a TimeZone aware way: Whenever we produce a DateTime we do it in UTC (e.g. using DateTime.UtcNow), and whenever we display one, we convert back from UTC to the user's local time.

That works fine, but I've been reading about DateTimeOffset and how it captures the local and UTC time in the object itself. So the question is, what would be the advantages of using DateTimeOffset vs what we have already been doing?

9条回答
闭嘴吧你
2楼-- · 2018-12-31 04:46

There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.

There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).

查看更多
孤独寂梦人
3楼-- · 2018-12-31 04:46

Most of the answers are good , but i thought of adding some more links of MSDN for more information

查看更多
墨雨无痕
4楼-- · 2018-12-31 04:52

The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.

XmlConvert.ToDateTimeOffset

XmlConvert.ToString

I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).

查看更多
登录 后发表回答