Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check valid date in java

I try to check a String input that is a valid date follow 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 cant 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. Are they support some methods for checking these rules ?
Thanks very much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
  • Apparently, by default the resolver style is not strict. Use .withResolverStyle(ResolverStyle.STRICT) to return a strict copy of the formatter.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading