DateTime Best Practices

Dan Rogers wrote a paper in 2004 about DateTime best practices.  http://msdn.microsoft.com/en-us/library/ms973825.aspx (Edit: I updated the link.) Here are some interesting points.

 There are a number of hidden gotchas in working with dates (“dates” can include times as well).

All dates should be in the same timezone when adding and subtracting intervals. Think of servers, clients, and daylight savings (ex: Oct 26, 2006 12:00 am + 3 hours should be 2:00 am, due to change in daylight savings). Best practice: convert dates to UTC (myTime.ToUniversalTime()), then perform math, then convert back.

At least in 1.0 and 1.1 framework, you had to make sure that when you serialized a date to xml it was in local format. XML Serialization would always adjust for local time when serializing and then deserializing – so if you convert to UTC first, you will get the wrong time. He indicates that Whidbey (now VS2005) will let you serialize to XML using UTC.

Best practice for wrapping a date in a class: Make the variable private and give two properties for accessing it: one for local and one for UTC. Always store the private var in UTC and then return it as requested.

CLR version 2.0 added daylight savings awareness. This eliminated a number of problems.

Another daylight-savings problem: accepting user input on days where the time changes. In the spring, 2:00 am never happens on the time-change day; in the fall, the 1:00 hour happens twice. For example, if a user inputs 1:10 am on that day, you don’t know if it’s the first 1:10 am that will be repeated again, or the second 1:10 am that is the repeat.

One practice that results from this has to do with .Now(). Don’t use DateTime.Now().ToUniversalTime(). Use DateTime.UtcNow() instead. This is to avoid that one problem hour in the fall – where you don’t know which 1:10 am it is.

No comments yet

Leave a comment