I find it curious that the most obvious way to create Date
objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
Two comments on the use of SimpleDateFormat.
IME that is better that instantiating an instance for each parse of a date.
Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:
Here's the output I get:
As you can see, it does handle both of your cases nicely.
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
java.time
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the
LocalDate
class.The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add: If you get a calendar instance and set the time using your date, this is how you get the validation.