import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
public class DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value,Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//format.setLenient(false); //设置输入的字符串形式必须符合此对象的格式化方法使用的形式
try {
if(toType == Date.class) { //当字符串向Date类型转换时
String[] params = (String[]) value; //request.getParameterValues()
return dateFormat.parse(params[0]);
} else if(toType == String.class) { //当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}把字符串解析成日期如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
public class Demo {
public static void main(String[] args) {
String strdate = "1990-12-32";
/*SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
try {
Date date = format.parse(strdate);
String localdate = format.format(date);
System.out.println(localdate);
} catch (ParseException e) {
System.out.println("格式不对");
}*/
//用这个类转换12-32时就会抛异常
DateLocaleConverter dcl = new DateLocaleConverter();
try {
dcl.convert(strdate, "yyyy-MM-dd");
} catch (Exception e) {
System.out.println("格式不对");
}
}
}

本文介绍了一个Java自定义日期类型转换器的实现,该转换器能够将字符串转换为日期或将日期转换为字符串,并提供了示例代码。

被折叠的 条评论
为什么被折叠?



