I've been playing with the DateTime object a lot recently and came across a bunch of weird inaccuracies, therefore, I decided to strip out all the unnecessary text from the Microsoft article and just post the best practices for using the DateTime object.
- When coding, store the time-zone information associated with a DateTime type in an adjunct variable.
- When testing, check to see that stored values represent the point-in-time value you intend in the time zone you intend.
- When coding, be careful if you need to perform DateTime calculations (add/subtract) on values representing time zones that practice daylight savings time. Unexpected calculation errors can result. Instead, convert the local time value to universal time, perform the calculation, and convert back to achieve maximum accuracy.
- When testing, calculate the value you expect to see in the XML string that is serialized using a machine local time view of the point in time being tested. If the XML in the serialization stream differs, log a bug!
- When writing code to serialize classes that have DateTime member variables, the values must represent local time. If they do not contain local time, adjust them prior to any serialization step, including passing or returning types that contain DateTime values in Web services.
- When coding, make DateTime member variables private and provide two properties for manipulating your DateTime members in either local or universal time. Bias the storage in the private member as UCT time by controlling the logic in your getters and setters. Add the XML serialization attributes to the local time property declaration to make sure that the local time value is what is serialized.
- When testing, if your programs accept user input specifying date and time values, be sure to test for data loss on "spring-ahead", "fall-back" 23- and 25-hour days. Also make sure to test for dates gathered on a machine in one time zone and stored on a machine in another time zone.
- When you are coding and desire to store current time represented as universal time, avoid calling DateTime.Now() followed by a conversion to universal time. Instead, call the DateTime.UtcNow function directly.