zoukankan      html  css  js  c++  java
  • 日期转换:Cannot format given Object as a Date (SimpleDateFormat的parse和format)

    1.错误信息

    Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
        at java.text.DateFormat.format(Unknown Source)
        at java.text.Format.format(Unknown Source)
        at .....QxtMessageUtils.main(QxtMessageUtils.java:210)
    


    2.错误分析与错误解决

    错误分析:
    源代码

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    LOGGER.info(sdf.format("20180208120005"));
    LOGGER.info(sdf.parse("20180208120005").getTime());
    

    本意,第一句日志打印格式化的日期,第二句打印时间戳。 手误把sdf.parse写成了sdf.format,导致第一句日志报错。
    错误解决:
    将sdf.format修改成sdf.parse即可。运行结果如下:
    2018-02-27 17:03:40 INFO  QxtMessageUtils:210 - Thu Feb 08 12:00:05 CST 2018
    2018-02-27 17:03:40 INFO  QxtMessageUtils:211 - 1518062405000

    3.引申:SimpleDateFormat.parse与SimpleDateFormat.format的区别

    SimpleDateFormat.parse方法如下:

    public Date parse(String source) throws ParseException
    {
        ParsePosition pos = new ParsePosition(0);
        Date result = parse(source, pos);
        if (pos.index == 0)
            throw new ParseException("Unparseable date: "" + source + """ ,
                pos.errorIndex);
        return result;
    }
    

     
    SimpleDateFormat.parse的作用是将格式化的字符串转换成Date值。
    SimpleDateFormat.format方法如下:

    public final String format(Date date)
    {
        return format(date, new StringBuffer(),
                      DontCareFieldPosition.INSTANCE).toString();
    }
    

     SimpleDateFormat.format的作用是将Date值转换成格式化的字符串。
    一定要注意parse和format的区别,尤其是参数类型和返回类型。


    原文链接:https://blog.csdn.net/hanchao5272/article/details/79390902

  • 相关阅读:
    Segmentation fault (core dumped)
    Missing separate debuginfos, use: debuginfo-install
    Qt学习资源
    Qt学习过程中遇到的问题
    深入浅出MFC--第一章
    MVC – 3.EF(Entity Framework)
    MVC基础知识 – 2.新语法
    js获取url参数值(HTML之间传值)
    解决IIS7、IIS7.5中时间格式显示的问题
    web.config详解 -- asp.net夜话之十一
  • 原文地址:https://www.cnblogs.com/baxianhua/p/12124308.html
Copyright © 2011-2022 走看看