While trying to validate user input, an input string of "1,5" results in a valid date:
var s = "1,5";
DateTime d;
var b = DateTime.TryParse(s,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out d);
Console.WriteLine("s: " + s);
Console.WriteLine("b: " + b);
Console.WriteLine("d: " + d);
Output is:
s: 1,5
b: True
d: 1/5/2021 12:00:00 AM
My intention was that "1,5" is not considered as a valid DateTime. Obviously, I'm wrong.
I've tried this both in .NET Framework 4.8 and .NET Core 5 with same results.
Having looked through the .NET sources of the DateTime.TryParse method, I still cannot figure out why this is considered a valid date.
In addition I would love to somehow prevent the method to recognize this as a valid date. My guess is to go with DateTime.TryParseExact but maybe there are better options.
My questions
- Why does
DateTime.TryParsein invariant culture consider "1,5" as a valid date. - How to prevent this behavior?