`

BeanUtils.copyProperties 日期转字符 日期转Long

阅读更多

建立自己的日期转换类

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.time.DateUtils;

public class DateConverter implements Converter {
	private static final SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	public Object convert(Class type, Object value) {
		if(value == null) {
	        return null;
	    }
	    if(value instanceof Date) {
	        return value;
	    }
	    if(value instanceof Long) {
	        Long longValue = (Long) value;
	        return new Date(longValue.longValue());
	    }
        try {
            return dateFormat.parse(value.toString());
            //return DateUtils.parseDate(value.toString(), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm" });
        } catch (Exception e) {
            throw new ConversionException(e);
        }
	}
}
 

 

使用自己的日期转换类替代默认的。如下面的main函数

public static void main(String[] args) {
                //替换
                ConvertUtils.register(new DateConverter(), Date.class);
		//ConvertUtils.register(new StringConverter(), String.class);
		A a = new A();
		a.date="2012-03-14 17:22:16";
		B b = new B();
		try {
			BeanUtils.copyProperties(b, a);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(b.getDate());
	}
 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics