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

166
Visualizações
check valid date in java

I tried to check a String input that is a valid date using the format dd/MM/yyyy like this:

String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)

But it can't check some rules below:

Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.

When I use input = "30/02/2022", it's legal. I use netbeans 8.2 and jdk 1.8. Do they support some methods for checking these rules?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There are two things you need to change in your formatter:

  • Use uuuu instead of yyyy. It's easy to try the latter, but y means "year within ERA". It doesn't know whether it's BC or AD. u means "year" including ERA information.
  • The default resolver style is SMART. Use .withResolverStyle(ResolverStyle.STRICT) to return a strict copy of the formatter.
over 4 years ago · Santiago Trujillo Relatório

0

You need to enable the strict mode of the DateTimeFormatter :

DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy")
                            .withResolverStyle(ResolverStyle.STRICT);

LocaleDate.parse("30/02/2022, formater); will then throw an exception.

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