• 日期转换: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

  • 相关阅读:
    [转]好习惯养成的10个步骤
    模拟资料
    [转]暗时间
    [转]30个小改变,造就你的卓越人生
    [转]Word 2007文档中图片不显示或对象不显示的解决方法
    ubuntu 10.04 安转2.6.38内核
    [转]可以让你少奋斗10年的工作经验
    [转]Vim 复制粘帖格式错乱问题的解决办法
    C# 获取类中所有的属性
    sql 脚本
  • 原文地址:https://www.cnblogs.com/baxianhua/p/12124308.html
Copyright © 2020-2023  润新知