Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse successfully parsing some numeric numbers

Tags:

c#

I have encountered an unexpected issue when parsing a string as a date.

DateTime dt;
bool parsed = DateTime.TryParse("119.08", out dt); 

After running the above code parsed is true and dt has a date of 8/1/0119. Why would this value parse as a date? There is an overload of the TryParse that takes an IFormatProvider and DateTimeStyles. Could this be used to resolve the issue.

like image 716
James Avatar asked Nov 16 '25 05:11

James


1 Answers

The reason it successfully parses is because of this on MSDN

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

So in your situation since 119 cannot be month (1-12) or a day (1-31) it tries its best and makes the assumption it must be year. Not sure about why it decides 08 is month vs day.

You need to tell the parse method what culture to use for parsing. You can use TryParseExact or TryParse. Here is how you would use TryParseExact:

CultureInfo enUS = new CultureInfo( "en-US" );
DateTime.TryParseExact( "119.08", "g", enUS,
                        DateTimeStyles.None, out dt );
// or this format
DateTime.TryParseExact( "119.08", "M/dd/yyyy hh:mm", enUS,
                        DateTimeStyles.None, out dt );

And here is some more info which I pulled right from the .NET FCL source code to explain how the parsing works. The first comment relates to your situation.

DateTimeParse

like image 124
CodingYoshi Avatar answered Nov 17 '25 19:11

CodingYoshi