然后是:
public class DateTypeConverter extends StrutsTypeConverter {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static final DateFormat[] ACCEPT_DATE_FORMATS = {
new SimpleDateFormat("yyyy-MM-dd HH:mm"),
new SimpleDateFormat(DEFAULT_DATE_FORMAT),
new SimpleDateFormat("dd/MM/yyyy"),
new SimpleDateFormat("yyyy/MM/dd")
};
public DateTypeConverter() {
}
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if (values[0] == null || values[0].trim().equals("")) {
return null;
}
for (DateFormat format : ACCEPT_DATE_FORMATS) {
try {
return format.parse(values[0]);
} catch (ParseException e) {
continue;
} catch (RuntimeException e) {
continue;
}
}
return null;
}
@Override
public String convertToString(Map context, Object o) {
if (o instanceof Date) {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
try {
return format.format((Date) o);
} catch (RuntimeException e) {
return "";
}
}
return "";
}
}
例子:
String date_str ="2010-11-09 01:20"; DateTypeConverter dtc = new DateTypeConverter(); Date d = (Date)dtc.convertFromString(null, new String[]{date_str}, null); System.out.println(d.toString());