如何检查 Date 对象或 Calendar 对象是否为有效日期(真实日期)?

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

SimpleDateFormat class的方法:

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.

Calendarclass的方法:

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.

检查格式的一致性或滚动日期。

我想确认带有 MM-DD-YYYY 的日期 (02-31-2016) 是否应该 return 无效,因为 2 月的 31 天不是真实日期所以 04-31-1980 也应该return无效。

不想使用 Java 8 中的 Joda 时间 API,但是对此有任何建议将不胜感激。

使用 Java 时间 API,可以使用 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);
}

此代码将抛出 DateTimeParseException,因为它不是有效日期。

默认情况下,格式化程序具有 SMART ResolverStyle:

By default, a formatter has the SMART resolver style.

但您可以通过在格式化程序实例上调用 withResolverStyle(resolverStyle) 来更改它。

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;
        }
}