Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check valid date in java

Tags:

java

date

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?

like image 445
hoàng nguyễn Avatar asked Aug 31 '26 01:08

hoàng nguyễn


1 Answers

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.
like image 154
Rob Spoor Avatar answered Sep 02 '26 15:09

Rob Spoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!