简体   繁体   中英

Java Date Validation Issue

Here is the validation code for Date of format MM/dd/yyyy.

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
Calendar cal = Calendar.getInstance();
Date myDate = formatter.parse("01/02/2014888");
cal.setTime(myDate);

When the date string is 01/02/2014888, it passes the validation. How can I make the validation correctly?

The Calendar class will allow you to create dates in the future, so 2014888 is a perfectly valid year, albeit a ways off. If you want to add additional constraints to the allowable date, you will need to check the values yourself, such as:

    if (cal.get(Calendar.YEAR) > endOfTime) {
        // do something about it
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM