SpringMVC日期类型转换问题三大处理方法归纳

方法一:实体类中加日期格式化注解

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date receiveAppTime;

方法二:控制器Action中加入一段数据绑定代码

 @InitBinder
 public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值,false:不能为空值
}

方法三:实现一个全局日期类型转换器并进行配置

  此方法较为复杂,请详细查看本人的这篇博文:SpringMVC配置全局日期转换器,处理日期转换异常

附加方法四:适合页面把日期类型转换成字符串且JSP,Freemark页面

JSP模版引擎方法:

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 
<fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>

Freemarker模版引擎方法

<input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" />
原文地址:https://www.cnblogs.com/zhujiabin/p/5144859.html