Java - 日期无效时抛出错误

Java - Throw error when date is invalid

我有以下代码:

SimpleDateFormat formatDDMMYYY = new SimpleDateFormat("dd/MM/yyyy");
Calendar quotationDay = Calendar.getInstance();
try {
    quotationDay.setTime(formatDDMMYYY.parse("06/13/2015"));
} catch (ParseException e) {
    throw new RuntimeException("Quotation date is in incorrect format.");
}

日期“06/13/2015”不正确,因为没有第 13 个月。 Java自动解析到下个月,2016年。有什么办法可以防止这种情况发生并抛出异常吗?

您需要设置

formatDDMMYYY.setLenient(false);

勾选spec

您应该按照 docs

中所述关闭宽大处理

Leniency

Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.

When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.