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)

     

      

     
  • 相关阅读:
    Java中的多态polymorphism
    Java中的“继承”
    面向对象(Oriented Object Programing)的本质
    Java设计方法原则
    Motor Parameter
    Motor Vocabuary
    JD
    CAN
    多个TXT文件合成一个,输出到excel里
    正则表达式
  • 原文地址:https://www.cnblogs.com/luyang08/p/14307242.html
Copyright © 2011-2022 走看看