日期处理
在实体方法中加入日期格式化注解
@DateTimeFormat(pattern="yyyy-MM-dd") private Date birthday;
在controller中加入数据绑定代码:
//日期参数将在 initBinder方法中被转换 @RequestMapping("/date") public String date(Date date){ System.out.println(date); return "student/info"; } @InitBinder public void initBinder(ServletRequestDataBinder binder){ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); }
全局日期类型转化器
注册全局转化器:配置文件
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 设置Converter转换器 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 设置多个转换器 -->
<property name="converters">
<list>
<bean class="com.yumeng.springmvc.convert.DateConverter "></bean>
</list>
</property>
</bean>
实现代码:
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; }
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'))!}" />

浙公网安备 33010602011771号