springmvc框架,前端页面yyyy-MM-dd HH:mm:ss和yyyy-MM-dd报错 使用@InitBinder绑定多个日期

springmvc框架提供了封装javaBean的功能,但是不会自动封装(比如java.util.Date类型),需要我们自行绑定。
这里介绍两种解决的办法:@InitBinder&@DateTimeFormat()

@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//转换日期 注意这里的转化要和传进来的字符串的格式一直 如2019-09-09 就应该为yyyy-MM-dd

	binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			if (text == null || text.isEmpty()) {
				setValue(null);
			} else {
				SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
				try {
					// 尝试第一种格式
					setValue(dateFormat1.parse(text));
				} catch (Exception e) {
					try {
						// 如果第一种格式失败,尝试第二种格式
						setValue(dateFormat2.parse(text));
					} catch (Exception ex) {
						throw new IllegalArgumentException("Invalid date/time format");
					}
				}
			}
		}
	});
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值