您的位置:首页 > 运维架构

BeanUtils.copyProperties支持Date类型

2017-01-05 14:29 357 查看
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.log4j.Logger;

/**
* @Title 扩展BeanUtils.copyProperties支持data类型
* @Description
* @author wangzs
* @date 2017-1-5
*/
public class BeanUtilsEx extends BeanUtils {
private static Logger logger = Logger.getLogger(BeanUtilsEx.class);

static {
ConvertUtils.register(new DateConvert(), java.util.Date.class);
ConvertUtils.register(new DateConvert(), String.class);
}

public static void copyProperties(Object target, Object source) {
// 支持对日期copy
try {
org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
} catch (IllegalAccessException | InvocationTargetException e) {
logger.error("扩展BeanUtils.copyProperties支持data类型:" + e.getMessage());
e.printStackTrace();
}
}
}


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;

/**
* @Title 扩展BeanUtils.copyProperties支持data类型
* @Description
* @author wangzs
* @date 2017-1-5
*/
public class DateConvert implements Converter {
@Override
public Object convert(Class class1, 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());
}
if (value instanceof String) {
String dateStr = (String) value;
Date endTime = null;
try {
String regexp1 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
String regexp2 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])(/t)([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
String regexp3 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])";
if (dateStr.matches(regexp1)) {
dateStr = dateStr.split("T")[0] + " " + dateStr.split("T")[1];
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
endTime = sdf.parse(dateStr);
return endTime;
} else if (dateStr.matches(regexp2)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
endTime = sdf.parse(dateStr);
return endTime;
} else if (dateStr.matches(regexp3)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
endTime = sdf.parse(dateStr);
return endTime;
} else {
return dateStr;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return value;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java