在我的应用程序中,我必须处理一个以字符串形式出现的日期,格式为yyyy-MM-dd。我无法更改基础类。在视图上,为方便用户,我希望它以dd.MM.yyyy格式显示。
据我了解,f:convertDateTime> 仅适用于 java.util.Date,不适用于假装为日期的字符串。所以我写了自己的转换器:
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date tempDate = inputFormat.parse((String) value);
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy");
return outputFormat.format(tempDate);
}
catch (ParseException e) {
return null;
}
}
这行得通,但感觉不对。从字符串转换为日期并返回到不同的字符串。另外,我喜欢 convertDateTime 如何处理时区和用户区域设置,这在这种方法中完全被忽略了。
有更好的解决方案吗?就像解析日期然后通过 f:convertDateTime 传递它?