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.
10 Comments:
Hey, thanks for posting this. I was trying to solve the same IFormatProvider (and had seen that with MC++ it was optional) but did not think of just throwing a null int there.
Glad to help. I found that problem a pain in the neck too.
thanks man.....great work !!
Perhaps worth mentioning though is that when the user enters 1/1/2008 instead of 01/01/2008, this method also falls over.
I catch an exception on the first attempt, and retry using "d/M/yyyy", which works.
Great work man thanks,I have searched many..:)))
Vivek
Thanks i was about to stop using dd/MM/yyyy
Thank you, SIR!! That's a nice way to solve a vexing problem!
Thanks a million!
Your post was of gr8 use!
Hi Shenoy,
Thanks! for providing a wonderful solution. I googled for solution and those didn't provide the expected result. But yours worked like a charm. Thanks! a lot.
-- Bala
rather than using a try/catch construct for different variations of expected date formats, use the overloaded method that accepts a list of accepted formats:
string[] validDateFormats = { @"M/d/yyyy", @"MM/dd/yyyy" };
myDate = = DateTime.ParseExact(processDateTextBox.Text, validDateFormats, null, System.Globalization.DateTimeStyles.None);
- and knowing is half the battle
Post a Comment
<< Home