Parse a non-standard date string into a System.DateTime object

The other day I had a date that was in the form of yyyyMMdd and I needed to parse that string into a System.DateTime object.  Just trying to parse the string into a System.DateTime object would not work:

String dateString = "20091016";
DateTime d = DateTime.Parse(dateString);

The above code results in an exception:

FormatException: String was not recognized as a valid DateTime.

I was guaranteed to have the date string in the form of yyyyMMdd so my initial thought was to use Substring to break it into the individual year, month, and day parts and create a new System.DateTime object from those pieces. 

But then I discovered that you can use the DateTime.ParseExact method and a System.Globalization.DateTimeFormatInfo object to specify the pattern for the date that is being parsed. 

Here is how I was able to parse a non-standard date string into a System.DateTime.

System.Globalization.DateTimeFormatInfo di;
di
= new System.Globalization.DateTimeFormatInfo();
di.FullDateTimePattern = "yyyyMMdd";

String dateString = "20091016";
DateTime d = DateTime.ParseExact(dateString, "F", di);

By the way, this is also a great way to parse a credit card expiration date that is in the form of MMyy to a System.DateTime.  Just use a pattern of MMyy for the FullDateTimePattern property.



Published 16 October 2009 09:22 PM by Jeff Widmer
Filed under: ,

Comments

# Twitter Trackbacks for Parse a non-standard date string into a System.DateTime object - Jeff Widmer's Blog [asp.net] on Topsy.com said on 16 October, 2009 10:11 PM

Pingback from  Twitter Trackbacks for                 Parse a non-standard date string into a System.DateTime object - Jeff Widmer's Blog         [asp.net]        on Topsy.com

# SGWellens said on 17 October, 2009 10:28 AM

If you are not confident in the format of the Date string, TryParseExact(...) is even better since it allows you to handle bad input gracefully without raising an exception.

# RichardD said on 18 October, 2009 09:37 AM

You don't have to create a new DateTimeFormatInfo and set the FullDateTimePattern - it's much simpler to use:

DateTime d = DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture);

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

Go

This Blog

News

Recommended Blogs

Syndication