To validate a date using SimpleDateFormat in Java, you can follow these steps:
Create a SimpleDateFormat object with the desired date format. For example:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Set the SimpleDateFormat object's lenient property to false. This will enable the strict parsing of dates.
Copy code
sdf.setLenient(false);
Parse the date string using the SimpleDateFormat object’s parse() method.
Date date = sdf.parse("23/06/2022");
If the date string is invalid, the parse() method will throw a ParseException. You can catch this exception and handle it accordingly.
try {
Date date = sdf.parse("23/06/2022");
} catch (ParseException e) {
// handle invalid date
}
Alternatively, you can use the parse() method that takes an additional ParsePosition argument, which allows you to check whether the entire string was successfully parsed or not.
ParsePosition pos = new ParsePosition(0);
Date date = sdf.parse("23/06/2022", pos);
if (pos.getErrorIndex() != -1) {
// handle invalid date
}