简体   繁体   English

SimpleDateFormat行为

[英]SimpleDateFormat behaviour

I have the following lines: 我有以下几行:

final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = simpleDateFormat.parse("2004-52-05");

I expect that an exception will be thrown in line 2, because '52' is not a valid month, but code runs and the date stored in d object is 我希望第2行会抛出异常,因为'52'不是有效的月份,但是代码运行并且存储在d对象中的日期是

Sat Apr 05 00:00:00 EEST 2008

Can somebody explain me why? 有人可以解释一下为什么吗?

If you want to create a date object that strictly matches your pattern, then set lenient to false. 如果要创建严格匹配模式的日期对象,请将lenient设置为false。

From Javadoc 来自Javadoc

Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. Calendar有两种解释日历字段的模式,lenient和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. 当日历重新计算get()返回的日历字段值时,所有日历字段都会进行规范化。 For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1. 例如,宽松的GregorianCalendar将MONTH == JANUARY,DAY_OF_MONTH == 32解释为2月1日。

Refer this for more information lenitent 有关lenitent的更多信息,请参阅此处

So add this.. 所以添加这个..

simpleDateFormat.setLenient(false);

This will throw an Exception as you were Expecting.. 这会像你期待的那样抛出Exception ......

java.text.ParseException: Unparseable date: "2004-52-05"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM