I was browsing Scott Hanselman's Developer Interview question list, and ran across this question:
What is wrong with DateTime.Parse(myString)?
While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first?
As MSDN Puts it: Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results.
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
In addition the locale problem, DateTime.Parse()
could also throw an exception which you would then have to catch. Use DateTime.TryParse()
or DateTime.TryParseExact()
instead.
Using the current thread culture on the system is often a bad idea, as is "try a variety of formats, and see if any of them work."
ParseExact with a specific culture is a much more controlled and precise approach. (Even if you specify the current culture, it makes it more obvious to readers that that's what's going on.)
As MSDN Puts it:
Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use the DateTime.Parse(String, IFormatProvider) method or one of the overloads of the ParseExact method and provide a format specifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With