时间类型,精度问题(Timestamp,Date)
经过调试,发现最后转换器会进入com.opensymphony.xwork.util.XWorkBasicConverter类(xwork.jar包)的对应的doConvertToDate方法,该方法内容:
private Object doConvertToDate(Map context, Object value, Class toType) {
Date result = null;
if (value instanceof String && value != null && ((String)value).length() > 0) {
String sa = (String) value;
Locale locale = getLocale(context);
DateFormat df = null;
if (java.sql.Time.class == toType) {
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
} else if (java.sql.Timestamp.class == toType) {
Date check = null;
SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.MEDIUM,
locale);
SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT,
locale);
SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
locale);
SimpleDateFormat rfc3339Format = new SimpleDateFormat(RFC3339_FORMAT);
SimpleDateFormat[] fmts = {fullfmt, dtfmt, dfmt, rfc3339Format};
for (int i = 0; i < fmts.length; i++) {
try {
//可以发现这里它会使用上面四种格式进行格式化(格式化失败进入异常),因此只有一个格式化会成功。我在页面中使用的<ww:datepicker name="act.actDate" label="活动时间"
format="%Y-%m-%d %H:%M" showstime="24">
</ww:datepicker>
只会被第三个格式化,而第三个格式化会被切去时间,所有出现了精度问题。
check = fmts[i].parse(sa);
df = fmts[i];
if (check != null) {
break;
}
} catch (ParseException ignore) {
}
}
} else if(java.util.Date.class == toType) {
Date check = null;
SimpleDateFormat d1 = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, locale);
SimpleDateFormat d2 = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
SimpleDateFormat d3 = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
SimpleDateFormat rfc3339Format = new SimpleDateFormat(RFC3339_FORMAT);
SimpleDateFormat[] dfs = {d1, d2, d3, rfc3339Format}; //added RFC 3339 date format (XW-473)
for (int i = 0; i < dfs.length; i++) {
try {
check = dfs[i].parse(sa);
df = dfs[i];
if (check != null) {
break;
}
}
catch (ParseException ignore) {
}
}
}
//final fallback for dates without time
if (df == null){
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
}
try {
df.setLenient(false); // let's use strict parsing (XW-341)
result = df.parse(sa);
if (! (Date.class == toType)) {
try {
Constructor constructor = toType.getConstructor(new Class[]{long.class});
return constructor.newInstance(new Object[]{new Long(result.getTime())});
} catch (Exception e) {
throw new XworkException("Couldn't create class " + toType + " using default (long) constructor", e);
}
}
} catch (ParseException e) {
throw new XworkException("Could not parse date", e);
}
} else if (Date.class.isAssignableFrom(value.getClass())) {
result = (Date) value;
}
return result;
}