Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with DateTime.Parse(myString)?

Tags:

c#

datetime

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?

like image 565
casademora Avatar asked Oct 02 '08 13:10

casademora


People also ask

What's wrong with a line like this DateTime parse Mystring?

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.

What does DateTime parse do?

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.


3 Answers

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.

like image 197
Joel Coehoorn Avatar answered Sep 18 '22 13:09

Joel Coehoorn


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.)

like image 31
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet


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.

like image 35
Torbjörn Gyllebring Avatar answered Sep 16 '22 13:09

Torbjörn Gyllebring