DateTime.TryParse converts decimal to datetime

Relativity picture Relativity · Jun 28, 2011 · Viewed 13.7k times · Source

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

Somebody please help me.

Answer

jason picture jason · Jun 28, 2011

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

This will not compile.

However, if you wrap it in quotes (and clean it up a little bit),

bool success = DateTime.TryParse("1.0228", out temporaryDateTimeValue);

then, yes, you will get true back. You need to read the documentation to understand why, but basically, there are many different ways to format dates and you stumbled on one (maybe M.yyyy?).

If you don't want it to parse, may I suggest

bool success = DateTime.TryParseExact(
                   "1.0228",
                   "yyyyMMdd", 
                   CultureInfo.InvariantCulture,
                   DateTimeStyles.None,
                   out temporaryDateTimeValue
               );

Then success is false.

I note from the remarks in the documentation:

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. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).

Because the DateTime.TryParse(String, DateTime) 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.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method or one of the overloads of the TryParseExact method and provide a format specifier.

Basically, TryParse "tries" very hard to parse the string you give it (although the "Try" really refers to the fact that the method returns a bool for success/failure indication).