Monday, June 05, 2006

Converting dd/MM/yyyy strings to Datetimes in .NET

It's not easy to find documentation on "How to parse a string into a DateTime variable in .NET?". I had to create an application that parsed a date entered as dd/MM/yyyy, and I had to ensure the code would run on any system, including U.S. based computers which would have the culture info set to MM/dd/yyyy.

All documentation points to the DateTime.Parse() method. Now this method is of no real use, because it always uses the culture information, which according to me is a no-entry zone because heck, all I want to do is parse a date, not change a whole culture.

Now there's this other function named DateTime.ParseExact( string s, string Format, IFormatProvider provider). This is EXACTLY what I needed, except I didn't know what to do with the provider parameter. All the documentation says is "An IFormatProvider that supplies culture-specific format information about s."

Another mention of the dreaded "culture". I tried to understand what this IFormatProvider was, and got to some custom class that converts strings to radixes (whatever they are). I don't know any culture that has radixes but I might have been living in a shell somewhere and all of this just happened.

Completely flummoxed, I thought, "to heck with this culture and IFormatProvider business" and passed "null" instead, and I got exactly what I wanted.

All you have to do is call:

DateTime d = DateTime.ParseExact( s, "dd/MM/yyyy", null);

and the string s will get converted to a DateTime, if it's in the dd/MM/yyyy format.

I wish they'd mentioned "optional" in the documentation for the provider parameter.