日期类型转换错误

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

一.局部方式

在对应的实体类上写上@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);
     }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值