Need help checking date

I have the code below, and it works pretty well, unless you enter something like 2/2/2011, you get the error "Document date is not a valid date." I would expect him to say: "The date of the document should be in the format MM / DD / YYYY."

Why newDate = dateFormat.parse(date);doesn't the string recognize this?

// 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 am trying to enforce strict adherence to the MM / DD / YYYY format. How can I change the code so that if the user enters "2/2/2011", he will display a message: "The date of the document should be in the format MM / DD / YYYY"?

+3
source share
2 answers

, SimpleDateFormat "2/2/2011", "02/02/2011". ParseException.

, dateFormat.format(newDate) "02/02/2011" "2/2/2011". , .

setLenient(false) :

: 3 , ; .

: - , . , .

(: java docs)

:

if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}
+4

, 02/02/2002

0

All Articles