Fun with time zones

Dates, times and time zones have always caused me headaches, and so now I generally try and store UTC dates whenever possible. This avoids any daylight saving problems, and using UTC dates is pretty straight forward in .NET.

Receiving dates in a particular time zone

There are some cases were other systems aren't so kind. This one system I recently worked with has some "interesting" way with dealing with dates. The API to the system returns key/string pairs, so naturally the string values need to be parsed into date objects (System.DateTime). The dates have a specific format: yyyy-mm-dd hh:mm:ss. Easy enough, except that the date strings for some keys are UTC and some in "London" time.

When parsing the UTC values, it is easy: just use the DateTimeStyles.AssumeUniversal value to the Parse method. However, it's not so easy with the "London" time, especially as the host I'm running on isn't guaranteed to be in the London time zone so can't simply fall back to 'local time'. It would be nice if the incoming date contained the UTC offset, but unfortunately it doesn't. I tried a few things like the TimeZoneInfo or DateTimeOffset classes, but then decided to try out NodaTime.

NodaTime

This library is a port/rewrite of the canonical Java date library, JodaTime. Within it, there is a nice API to convert between arbitrary time zones, which is just what I need. It turns out to be fairly straight forward:

public DateTime ParseThirdPartySystemDateTime(string key, string dateTimeValue) {
 LocalDateTime localDateTime;
 if (!LocalDateTime.TryParseExact(dateTimeValue, "yyyy-MM-dd HH:mm:ss", null, out localDateTime))
  return DateTime.MinValue;

 // NB: just an example...this is configurable in reality
 var timeZoneName = key == "UserEnteredDate" ? "Europe/London" : "UTC";
 DateTimeZone tz = DateTimeZone.ForId(timeZoneName);
 return localDateTime.InZoneLeniently(tz).ToDateTimeUtc();
}

A great library, thanks Jon Skeet!


Comment Guidelines
See the FAQ for details on the full rules and guidelines. No Spam. Write clearly and thoughtfully - no bad language.