1.编写日期转换器
package com.ync365.common.spring;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* ClassName:DateConvert 日期转换器 <br/>
* Date: 2017年3月1日 下午4:26:33 <br/>
* @author ztd
* @version
* @see
*/
public class DateConvert implements Converter<String, Date> {
private final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
private final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final int leng_yyyyMMdd = 10;
private final int leng_yyyyMMddHHmmss = 19;
@Override
public Date convert(String source) {
if(source.length() == leng_yyyyMMdd) {
try {
return yyyyMMdd.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
} else if(source.length() == leng_yyyyMMddHHmmss) {
try {
return yyyyMMddHHmmss.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
2.配置到 spring-mvc.xml 配置文件中
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.ync365.common.spring.DateConvert" />
</list>
</property>
</bean>
3.将配置添加到 mvc:annotation-driven 标签中
<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>