Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

334
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda