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?
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 whatDateTimeOffset
does internally).Most of the answers are good , but i thought of adding some more links of MSDN for more information
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).