前提:1.实体类的日期属性类型为Date 2.前端提交的日期类型为字符串
解决方法:
方法1、在相应的controller中定义一下方法
/**
* 将前端字符串格式的日期转换为date类型
* @param binder
*/
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
这样前端传递yyyy-MM-dd的字符串日期时,就能转换为实体类属性的Date类型
若想接收其他日期格式,只需要修改以上方法的SimpleDateFormat格式类型就好。
方法2:使用springmvc注解方式自定义date类型格式
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;