SpringMVC中日期格式的转换

时间:2022-06-03 18:09:16

1.自定义DataConvertor类, 并实现Convertor接口

package hstc.edu.cn.controller.convertor;

import org.springframework.core.convert.converter.Converter;
import org.springframework.expression.ParseException;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by win8 on 2017/4/13.
*/
public class DateConverter implements Converter<String, Date> {
public Date convert(String s) {
SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return simpleDateFormat.parse(s);
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
return null;
}
}

2.在springmvc.xml配置文件中注册转换器

 <mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="hstc.edu.cn.controller.convertor.DateConverter"></bean>
</set>
</property>
</bean>

 3.在视图中使用

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<td><fmt:formatDate value="${blog.releaseDate}" pattern="yyyy-MM-dd HH:mm:ss"/> </td>

 4.效果

SpringMVC中日期格式的转换