Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!