The problem with DateTime.

Posted by

The .NET Base Class Library team have a couple of posts on their blog, about the new DateTimeOffset class in the BCL (title "A Brief History of DateTime" and "A Brief History of DateTime Follow-up").

In those posts, they go to some lengths to describe the design descisions around the DateTime structure as well as the reasoning for the new DateTimeOffset structure (by the way, you should read the name of the new type as "Date, Time, Offset" -- as in, it contains a date, a time and an offset). Now, I've done quite a lot of work with DateTime in the past, and a lot of that work has revolved around presenting time-based information to users in different timezones from a central server. And I will be the first to admit that DateTimeOffset is a welcome addition (too bad I have to wait for version 3.5 of the framework!)

But some people seem to have trouble using DateTime in the manner for which it was intended. In my personal opinion, the only thing "wrong" with the implementation of DateTime as it stands is the fact that there are two methods for getting the "current" time: DateTime.Now and DateTime.UtcNow. If they'd simply not included the DateTime.Now property, I'm quite sure that most of the trouble people have with the class would be a thing of the past.

You see, in our application, DateTime.Now is basically a "banned" property. If ever you see DateTime.Now in the code, it is usually a bug. Essentially, all work we do with DateTimes is done in UTC and only at the very last minute are those dates converted to local time for display (usually not via ToLocalTime, simply because the person displaying the DateTime is hardly ever in the same timezone as the server on which the application is running).

DateTimeOffset solves some of the problems we have at the moment were we have to be quite careful when accepting DateTime values from users, because we have to ensure that they're in UTC before we do anything with them. But other than that particular scenario, the DateTime object is more than capable of doing everything that people seem to be having trouble with.

blog comments powered by Disqus