Skip to content
Advertisement

How to disable date auto update/correct/adjust in Java?

Im trying to check the format of the Date.

Implementation: Get Date format yyyy-MM-dd then if i input beyond month 12 and day 30 or 31 depend on the month it must show error.

The pattern will work if I manually setup a date in String, but the date must come from Date to String but the Date will auto adjust.

Try the code here: https://www.programiz.com/java-programming/online-compiler/

JavaScript

The manual with String only. This will work.

JavaScript

Advertisement

Answer

If you switched to a java.time.LocalDate, you could use the Exceptions that get thrown when you try to initialize a LocalDate with invalid values:

Let’s say you just want to create a LocalDate with given int values for year, month of year and day of month. You could try to initialize one and print the error message of the DateTimeException thrown.

e.g. the following code will print an error:

JavaScript

The message printed will be

JavaScript

You could find out an invalid month of year, too, e.g. LocalDate.of(2022, 13, 31) would cause the above code to print

JavaScript

And a valid input would simply print the toString() method of the successfully created LocalDate. Use a DateTimeFormatter if you want different output.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement