java.text.ParseException: Unparseable date:"May 13, 2010 21:00:00 AM"

使用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的结果即可发现原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值