使用propertyEditor处理字符串和时间的转换问题

在平时的程序开发过程中,很多时候需要将String和Date 进行转换,例如管理系统中日期的录入,一般我们自己编写一个工具类来实现这个功能,不过在spring中,这个过程就更简单了,下面就做一个简单的例子

首先我们创建一个Person类,他有他的生日

Person.java

  1. package rexcel.study.spring.beans.Beanwrapper;   
  2.   
  3. public class Person {   
  4.     private java.util.Date birthDay;   
  5.   
  6.     public java.util.Date getBirthDay() {   
  7.         return birthDay;   
  8.     }   
  9.   
  10.     public void setBirthDay(java.util.Date birthDay) {   
  11.         this.birthDay = birthDay;   
  12.     }   
  13.        
  14. }   

接下来我们要给他设定一个初始的生日,当然仅是给定一个String类型"dd-MM-yyy",因为我输入的时候就是这个类型,我也懒得去修改,那我们要怎么做才好呢?

Test.java

  1. package rexcel.study.spring.beans.Beanwrapper;   
  2.   
  3. import java.text.SimpleDateFormat;   
  4. import java.util.Date;   
  5.   
  6. import org.springframework.beans.BeanWrapper;   
  7. import org.springframework.beans.BeanWrapperImpl;   
  8. import org.springframework.beans.propertyeditors.CustomDateEditor;   
  9.   
  10. public class Test{   
  11.   
  12.     /**  
  13.      * @param args  
  14.      * 使用propertyEditor处理字符串与时间的转换  
  15.      */  
  16.     public static void main(String[] args) {   
  17.         // TODO Auto-generated method stub   
  18.         SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyy");   
  19.         //创建propertyEditor   
  20.         CustomDateEditor editor=new CustomDateEditor(sdf,false);   
  21.         Person person =new Person();   
  22.         BeanWrapper bwPerson =new BeanWrapperImpl(person);   
  23.         //设定editor   
  24.         bwPerson.registerCustomEditor(Date.class,editor);   
  25.         //给出生日 String类型  
  26.         bwPerson.setPropertyValue("birthDay","04-03-1986");   
  27.   
  28.         System.out.println(bwPerson.getPropertyValue("birthDay"));   
  29.     }   
  30.   
  31. }   

好了,我们试试看,运行:

Tue Mar 04 00:00:00 CST 1986

一切搞定

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值