方法一:实体类中加日期格式化注解
@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:不能为空值
方法三:适合页面把日期类型转换成字符串且JSP
//jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> //Freemarker <fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/> <input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" />
方法四:实现一个全局日期类型转换器并进行配置(参考)
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.doje.XXX.web.DateConverter" /> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService" />
public class DateConverter implements Converter<String, Date> { @Override public Date convert(String source) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { return dateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } return null; }