---
title: "BeanUtils.copyProperties 日期转字符 日期转Long"
author: "thomaslee007"
date: "2012-03-15T11:05:25Z"
tags: []
categories: ["编程语言"]
slug: "beanutils-copyproperties-long"
draft: false
lastmod: "2012-03-15T11:05:25Z"
id: 1454045
url: "https://thomaslee007.iteye.com/blog/1454045"
---

建立自己的日期转换类

```
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());
	}
```