Why does DateTime.TryParse see "1,5" as valid (and how to prevent)?

Viewed 78

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

.NET Fiddle

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

  1. Why does DateTime.TryParse in invariant culture consider "1,5" as a valid date.
  2. How to prevent this behavior?
1 Answers

It's parsing it as "Month, Day" in the current year - that's why it allows it.

DateTime.TryParse() is notoriously permissive - the advice is generally to use DayTime.TryParseExact() to avoid such things (as you suggest yourself).

There's no better way to solve this than using DateTime.TryParseExact().

This behaviour is actually documented:

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

So it parses the month and day number, and then sets the year to the current date's year and the time to midnight.

Related