TryParseExact and UTC DateTime

I’m in the midst of SIP-land at the moment and looking at the expiry time of requests. After discovering a subtle difference in the parsing of DateTime strings between my development machine and the production servers, we’re now using the DateTime.TryParseExact() method to specify exactly what the service should expect to see.

One of the parameters allows you to specify a DateTimeStyle and as I knew the time was going to be in UTC time I chose the AssumeUniversal DateTimeStyle. The MSDN information for DateTimeStyle defines AssumeUniversal indicating

“that if no time zone is specified in the parsed string, the string is assumed to denote a Coordinated Universal Time (UTC). Cannot be used with AssumeLocal or RoundtripKind.”

It seemed to be exactly what I wanted until I started testing it. The time I was getting back was an hour ahead so it was being converted to local time as we’re currently in British Summer Time (GMT+1) here.

The solution was to use the AdjustToUniversal DateTimeStyle instead. I’ve tested this with my system time in British Summer Time and without the local adjustment and it works fine for both.

Here’s the small console application I wrote to test the TryParseExact() method. Try it with AssumeUniversal instead of AdjustToUniversal if you want to see the difference for yourself.

class Program
{
static void Main(string[] args)
{
DateTime requestExpires;
DateTime.TryParseExact("23/05/2008 08:30:49", "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.AdjustToUniversal, out requestExpires);
Console.WriteLine(requestExpires);
Console.ReadLine();
}
}

2 thoughts on “TryParseExact and UTC DateTime”

  1. Thanks for this – old blog posts never die!

    But I think maybe the best answer is to use BOTH AssumeUniversal AND AdjustToUniversal:
    DateTime.TryParseExact(group.Value, this.customParseText, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out dateTime);

Leave a Reply

Your email address will not be published. Required fields are marked *