今天在改bug的时候,碰到了后台报错:java.text.ParseException: Unparseable date
话不多说,上报错部分的演示代码
package com.whir.ezoffice.hrm.kq.actionsupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class T {
public static void main(String[] args) {
try {
String dateStr="2018-06-27";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");
Date date = sdf.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
上图代码运行后,报错如下
报错原因:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss"),这里的参数精度高于我想要解析的日期字符串的精度
正确代码如下
package com.whir.ezoffice.hrm.kq.actionsupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class T {
public static void main(String[] args) {
try {
String dateStr="2018-06-27 12:02:06";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");
Date date = sdf.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
总结:SimpleDateFormat只能解析比自己精度高或与自己精度相同的日期字符串