SimpleDateFormat 行为
SimpleDateFormat behaviour
我有以下几行:
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = simpleDateFormat.parse("2004-52-05");
我预计第 2 行会抛出异常,因为 '52' 不是有效月份,但代码运行并且 d 对象中存储的日期是
Sat Apr 05 00:00:00 EEST 2008
有人可以解释一下为什么吗?
If you want to create a date object that strictly matches your
pattern, then set lenient to false.
来自 Javadoc
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.
请参阅此以获取更多信息lenitent
所以添加这个..
simpleDateFormat.setLenient(false);
这将像您期望的那样抛出 Exception
..
java.text.ParseException: Unparseable date: "2004-52-05"
我有以下几行:
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = simpleDateFormat.parse("2004-52-05");
我预计第 2 行会抛出异常,因为 '52' 不是有效月份,但代码运行并且 d 对象中存储的日期是
Sat Apr 05 00:00:00 EEST 2008
有人可以解释一下为什么吗?
If you want to create a date object that strictly matches your pattern, then set lenient to false.
来自 Javadoc
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.
请参阅此以获取更多信息lenitent
所以添加这个..
simpleDateFormat.setLenient(false);
这将像您期望的那样抛出 Exception
..
java.text.ParseException: Unparseable date: "2004-52-05"