package cn.itcast.commons;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;
/**
* 把String轉換成java.util.Date的類型轉換器
* @author qdmmy6
*
*/
public class DateConverter implements Converter {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if(value == null) return null;//如果要轉換成值爲null,那麼直接返回null
if(!(value instanceof String)) {//如果要轉換的值不是String,那麼就不轉換了,直接返回
return value;
}
String val = (String) value;//把值轉換成String
// 使用SimpleDateFormat進行轉換
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(val);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}