Parsing dates when ASP.NET’s DateTime.Parse doesn’t work

Posted by William on Jul 26, 2009

Has DateTime.Parse ever thrown the following exception when you passed it a legally formatted value, leaving you bemused as to why it can’t parse it?

String was not recognized as a valid DateTime

As powerful as DateTime.Parse is, it cannot handle every representation of a date/time value without a little help from you, the developer.

External sources of data are prime culprits to raise this issue. Recently I was working with a Twitter XML feed which returned it’s <created_at /> element with a date formatted as “Mon Jul 20 12:19:00 +0000 2009″. Using DateTime.Parse on this throws the exception String was not recognized as a valid DateTime. Fortunately getting this value parsed to a proper DateTime type is easy.

Instead of calling DateTime.Parse call DateTime.ParseExact and pass a simple date formatting string as a helper to the parser. For example.

1
2
string value = "Mon Jul 20 12:19:00 +0000 2009"; // This would probably be read from an external source
DateTime created_at = DateTime.ParseExact(value, "ddd MMM dd HH:mm:ss zz00 yyyy", null);

In most cases passing null as the third parameter will be fine, but if you need to pass an IFormatProvider to further qualify the string being parsed you can pass one here.

1
2
3
4
5
using System.Globalization;
 
string value = "Mon Jul 20 12:19:00 +0000 2009"; // This would probably be read from an external source
CultureInfo ci = new CultureInfo("en-GB");
DateTime created_at = DateTime.ParseExact(value, "ddd MMM dd HH:mm:ss zz00 yyyy", ci);

The key thing to know throughout this is your formatting strings. The .NET framework provides this very powerful means of formatting numeric, enumeration, and date and time base data types and I highly recommend that any .NET developer ensures they understand how to use them to their full advantage.