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.