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

  • 相关阅读:
    CHAR和HEX互相转换
    Delphi之TComponent类
    Delphi 延迟函数 比sleep 要好的多
    Delphi中三种延时方法及其定时精度分析
    Cport 应用集合
    重命名数据库时提示无法用排他锁锁定数据库
    Bugzilla在XP下安装
    Web service 超过了最大请求长度
    调用webservice时提示对操作的回复消息正文进行反序列化时出错
    c# IL 指令解析
  • 原文地址:https://www.cnblogs.com/baxianhua/p/12124308.html
Copyright © 2020-2023  润新知