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.
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 currentDateTimeFormatInfo
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 thestring
representation of a date and time using the formatting rules of the current culture, trying to parse a particularstring
across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use theDateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)
method or one of the overloads of theTryParseExact
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).