SimpleDateFormat的坑

来源:互联网 发布:淘客群管软件 编辑:程序博客网 时间:2024/06/14 09:38

问题是一个错误的日期,没有得到正确的ParseException.

查了下发现SimpleDateFormat有个方法,是指定是否参与计算的。

比如13/01/2017 , MM/dd/yyyy来格式化,本来应该是错误的,因为月份是13了。

但是因为指定了这个参数,结果参与计算,就没有得到异常而是得到了01/01/2018这个日期。


代码如下:


String s = "16/03/2017";SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");sdf.setLenient(true); ///  <------------- 关键是这里System.out.println(sdf.parse(s));


设置为true之后没有得到Exception,而是得到计算的日期。要想得到异常要设置成false

原创粉丝点击