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

posted @ 2019-12-31 14:35  筱筱的春天  阅读(2660)  评论(0编辑  收藏  举报