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