在平时的程序开发过程中,很多时候需要将String和Date 进行转换,例如管理系统中日期的录入,一般我们自己编写一个工具类来实现这个功能,不过在spring中,这个过程就更简单了,下面就做一个简单的例子
首先我们创建一个Person类,他有他的生日
Person.java
- package rexcel.study.spring.beans.Beanwrapper;
- public class Person {
- private java.util.Date birthDay;
- public java.util.Date getBirthDay() {
- return birthDay;
- }
- public void setBirthDay(java.util.Date birthDay) {
- this.birthDay = birthDay;
- }
- }
接下来我们要给他设定一个初始的生日,当然仅是给定一个String类型"dd-MM-yyy",因为我输入的时候就是这个类型,我也懒得去修改,那我们要怎么做才好呢?
Test.java
- package rexcel.study.spring.beans.Beanwrapper;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.springframework.beans.BeanWrapper;
- import org.springframework.beans.BeanWrapperImpl;
- import org.springframework.beans.propertyeditors.CustomDateEditor;
- public class Test{
- /**
- * @param args
- * 使用propertyEditor处理字符串与时间的转换
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyy");
- //创建propertyEditor
- CustomDateEditor editor=new CustomDateEditor(sdf,false);
- Person person =new Person();
- BeanWrapper bwPerson =new BeanWrapperImpl(person);
- //设定editor
- bwPerson.registerCustomEditor(Date.class,editor);
- //给出生日 String类型
- bwPerson.setPropertyValue("birthDay","04-03-1986");
- System.out.println(bwPerson.getPropertyValue("birthDay"));
- }
- }
好了,我们试试看,运行:
Tue Mar 04 00:00:00 CST 1986
一切搞定