一.局部方式
在对应的实体类上写上@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")注解,后面的格式需要按照要求来
二.全局方式
实现Converter接口
public class StringToDateConverter implements Converter<String, Date> {
/**
* 用于把 String 类型转成日期类型
*/
@Override
public Date convert(String source) {
DateFormat format = null;
try {
if(StringUtils.isEmpty(source)) {
throw new NullPointerException("请输入要转换的日期");
}
format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(source);
return date;
} catch (Exception e) {
throw new RuntimeException("输入日期有误");
}
}
}
在 spring 配置文件中配置类型转换器。
<!-- 配置类型转换器工厂 -->
<bean id="converterService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 给工厂注入一个新的类型转换器 -->
<property name="converters">
<array>
<!-- 配置自定义类型转换器 -->
<bean class="com.gaipian.web.converter.StringToDateConverter"></bean>
</array>
</property>
</bean>
在 annotation-driven 标签中引用配置的类型转换服务
<!-- 引用自定义类型转换器 -->
<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>
三.属性编辑器(spring3.1之前)
在Controller类中通过@InitBinder完成
/**
* 在controller层中加入一段数据绑定代码
* @param webDataBinder
*/
@InitBinder
public void initBinder(WebDataBinder webDataBinder) throws Exception{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
simpleDateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
}
备注:自定义类型转换器必须实现PropertyEditor接口或者继承PropertyEditorSupport类
写一个类 extends propertyEditorSupport(implements PropertyEditor){
public void setAsText(String text){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy -MM-dd hh:mm");
Date date = simpleDateFormat.parse(text);
this.setValue(date);
}
public String getAsTest(){
Date date = (Date)this.getValue();
return this.dateFormat.format(date);
}
}

本文介绍了在Spring中处理日期类型转换的三种方法:一是在实体类上使用@DateTimeFormat进行局部转换;二是通过实现Converter接口并配置全局类型转换器;三是针对Spring 3.1之前的版本,利用属性编辑器进行转换。
1151

被折叠的 条评论
为什么被折叠?



