简体   繁体   中英

How to check if a Date object or Calendar object is a valid date (real date)?

SimpleDateFormat class's method:

public void setLenient(boolean lenient)

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

or the Calendar class's method:

public void setLenient(boolean lenient)

Specifies whether or not date/time interpretation is to be lenient. With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient.

checks for the conformity of the format or rolls the date.

I would like to confirm if the date with MM-DD-YYYY (02-31-2016) should return invalid as 31day in feb is not a real date so should 04-31-1980 also return invalid.

Would not like to use Joda time API from Java 8 however any suggestion on this would be greatly appreciated.

Using Java Time API, this can be done using the STRICT ResolverStyle :

Style to resolve dates and times strictly.

Using strict resolution will ensure that all parsed values are within the outer range of valid values for the field. Individual fields may be further processed for strictness.

For example, resolving year-month and day-of-month in the ISO calendar system using strict mode will ensure that the day-of-month is valid for the year-month, rejecting invalid values.

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
                                                   .withResolverStyle(ResolverStyle.STRICT);
    LocalDate.parse("02-31-2016", formatter);
}

This code will throw a DateTimeParseException since it is not a valid date.

By default, a formatter has the SMART ResolverStyle :

By default, a formatter has the SMART resolver style.

but you can change this by calling withResolverStyle(resolverStyle) on the formatter instance.

final static String DATE_FORMAT = "dd-MM-yyyy";

public static boolean isDateValid(String date) 
{
        try {
            DateFormat df = new SimpleDateFormat(DATE_FORMAT);
            df.setLenient(false);
            df.parse(date);
            return true;
        } catch (ParseException e) {
            return false;
        }
}

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