I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message “The Document Date is not a valid date”. I would expect that it would say “The Document Date needs to be in the format MM/DD/YYYY”.
Why does the line newDate = dateFormat.parse(date); not catch that?
// checks to see if the document date entered is valid
private String isValidDate(String date) {
// set the date format as mm/dd/yyyy
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date newDate = null;
// make sure the date is in the correct format..
if(!date.equals("mm/dd/yyyy")) {
try {
newDate = dateFormat.parse(date);
} catch(ParseException e) {
return "The Document Date needs to be in the format MM/DD/YYYY\n";
}
// make sure the date is a valid date..
if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
return "The Document Date is not a valid date\n";
}
return "true";
} else {
return "- Document Date\n";
}
}
EDIT: I’m trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters “2/2/2011”, it will display the message: “The Document Date needs to be in the format MM/DD/YYYY”?
As already mentioned, the
SimpleDateFormatis able to parse "2/2/2011" as if it is "02/02/2011". so noParseExceptionis thrown.On the other hand,
dateFormat.format(newDate)will return "02/02/2011" and is compared against "2/2/2011". The two strings aren’t equal, so the second error message is returned.setLenient(false)will not work in this case:(source: java docs)
you can use a regular expression to manually check the string format: