Thursday, March 22, 2007

Timezone aware DateTime stucture in .Net 2.0 ?

The last year and a half I have been working on a project based on .Net framework 1.1, that (among other things) involved handling multiple time zones. If you have ever worked on such a project you either did it wrong without knowing or you have spent a whole lot of time getting it nearly 100% right. The biggest problems are the XML serialization that always assumes en DateTime represents local time, and the lack of a specific Date-only data type which is time zone independent. When it comes to handling DateTimes in different time zones .Net framework 1.1 just doesn't cut it.
Framework 2.0 brings partly good news, only last week I happened to 'intellisense' over a new property on the DateTime structure; DateTime.Kind. It seems that Microsoft has found a use for 2 unused bits in the 64 bits that hold up the data for a DateTime structure. These 2 bits were not enough to store the actual UTC offset. Instead they choose for three possible values, Local, UTC and Unknown. This is a big improvement because it solves the incorrect XML serialization problem of UTC DateTimes.
The lack of the actual UTC offset in the DateTime structure still has the downside of not being able to handle time zones other than UTC or your own (the one configured in the regional settings) without storing the offset in a separate field and doing your own transformations. Of course the DateTime being a structure which cannot be inherited from doesn't really help to create a generic solution for this one. Second it causes an ambiguity in the hour in the fall when the clock shifts to daylight saving time. This can cause an UTC time being converted to local and back to UTC not to be the same as the original. Last time this happened some of our unit tests broke because the daily build cycle runs exactly within this hour.