SimpleDateFormat未抛出ParseException

关于SimpleDateFormat的不严格性【技术探讨】
今天一组员写了几段Java代码,发现如下问题:
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(sdf.parse(timestamp.toString()));

此语句居然没有报异常,于是写了下面一段代码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println(sdf.parse("2017-06-08 15:49:53.395"));
效果同第一段代码一样,没有报异常,输出为Tue Dec 06 00:08:15 CST 2016

针对于些,找了网上的一些内容,在
http://bbs.csdn.net/topics/190075531第9楼找到的结果
根据此,找到相关的JavaDoc内容,看到如下内容

SimpleDateFormat 继承于DateFormat

SimpleDateFormat.parse()->DateFormat.parse(String source)->DateFormat.parse(String source, ParsePosition pos)->SimpleDateFormat.parse(String source, ParsePosition pos)

根据DateFormat的public abstract Date parse(String source, ParsePosition pos)方法注解,存在如下内容:
     * <p> 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 {@link #setLenient(boolean) setLenient(false)}.

译文如下:

    一般来说,解析是不严格的。如果输入不符合Object的格式(即定义的SimpleDateFormat),仍会被解析成一个日期,这个解析是成功的。开户者如果坚持严格校验输入的格式的话,请使用方法etLenient(boolean) 设置属性setLenient(false)


根据此,写了如下代码:
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setLenient(false);
        System.out.println(sdf.parse("2017-06-08 15:49:53.395"));
正常抛出异常ParseException,测试通过,只是以后再做解析时,需要再多加一行代码了

此问题,我在Java 6u45 32位,Java 8u131 64位中测试通过,应该普遍存在于Java6~Java8中,望使用者注意

附加信息,在某些情况下,SimpleDateFormat会自动处理,即setLenient(true)的情况下,并且,有些情况下,即使setLeniet(true),也会抛出ParseException。具体逻辑,可能还需要根据源码再行分析……
 
感谢 http://bbs.csdn.net/topics/190075531

原文:https://blog.csdn.net/lengmohui668/article/details/79678047 

原文地址:https://www.cnblogs.com/hahajava/p/10064027.html