使用SimpleDateFormat从数据库取出带时分秒的日期类型后转换为“年月日”时报错Unparseable date
源代码
private void getDayInterval(Date beginTime, Date endTime) {
DateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate;
Date endDate;
try {
beginDate = simpleFormat.parse(beginTime.toLocaleString());
endDate = simpleFormat.parse(endTime.toLocaleString());
} catch (ParseException e) {
//记录日志
}
}
这是因为toLocaleString()方法会转换为本机的日期表示方式,而SimpleDateFormat的parse()方法只能转换YYYY-mm-dd或者YYYY/mm/dd之类的,而toLocaleString()方法可能会转换为May 13, 2010 21:00:00 AM之类的字符串,所以在parse的时候就会报错。此外,toLocaleString方法也已经被标记为Deprecated,不建议使用
解决:使用format方法
private void getDayInterval(Date beginTime, Date endTime) {
DateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate;
Date endDate;
try {
String beginFormat = simpleFormat.format(beginTime);
String endFormat = simpleFormat.format(endTime);
beginDate = simpleFormat.parse(beginFormat);
endDate = simpleFormat.parse(endFormat);
} catch (ParseException e) {
//自定义处理
}
}
调试的时候可以打印出toLocaleString的结果即可发现原因。