zoukankan      html  css  js  c++  java
  • DateFormat采坑

    无意发现一个dateformat的问题

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date eventDate = dateFormat.parse("2021-01-22 12:34:22");
            System.out.println(dateFormat.format(eventDate));

    //结果 : 20201130220212

    2021年转换成2020年,没有抛出
    ParseException 有点费解

    看源码解释,默认是lenient的,如果一个格式错误,但是还能继续解析就返回成功,不抛出异常。如果设置成严格setLenient(false),就会抛出异常

         * <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)}.
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            dateFormat.setLenient(false);
            Date eventDate = dateFormat.parse("2021-01-22 12:34:22");
            System.out.println(dateFormat.format(eventDate));
    //执行结果:

    Exception in thread "main" java.text.ParseException: Unparseable date: "2021-01-22 12:34:22"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at com.idss.test.main(test.java:23)

     

      

     
  • 相关阅读:
    P3619 魔法
    【HAOI2014】遥感监测
    cdcq的独立博客上线辣!-> http://cdcq.coding.me/blog/
    重复型图床
    【BZOJ1213】高精度开根
    前后端技术
    【HAOI2011】problem b
    【HAOI2011】problem a
    【BZOJ4553】【TJOI2016】【HEOI2016】序列
    【HAOI2015】 T1
  • 原文地址:https://www.cnblogs.com/luyang08/p/14307242.html
Copyright © 2011-2022 走看看