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 SimpleDateFormat is able to parse "2/2/2011" as if it is "02/02/2011". so no ParseException is 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:
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
(source: java docs)
you can use a regular expression to manually check the string format:
if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
// parse the date
} else {
// error: wrong format
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With