Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda