为什么我可以用 SimpleDateFormat 解析“2015-18-32”?

Why can I parse "2015-18-32" with SimpleDateFormat?

我试图回答一个问题,我准备了一个小例子,希望能提供一些成功和错误消息,在我尝试了代码工作之后:

代码

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// correct format in string but totally wrong data for a date.
String curDate = "2015-18-32";
Date parsedDate = null;
try {
    parsedDate = format.parse(curDate);
} catch (ParseException e) {}

System.out.println(parsedDate);

输出

Sat Jul 02 00:00:00 CEST 2016

DEMO HERE

我知道结果日期只是有效日期 (2015-12-31) 加上 6 个月零 1 天,但这对我来说似乎不正确。我是不是误会了SimpleDateFormat

来自文档:

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

这实际上是在日期上增加了 6 个月零 2 天,每个月和每个月的日期都超出范围,最终是 2016 年 7 月 2 日。

另请参阅下面 jwenting 关于 java.util.Calendar 宽大处理的评论。