2

在我的应用程序中,我必须处理一个以字符串形式出现的日期,格式为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 传递它?

4

1 回答 1

2

后端(豆):

String string = "2014-05-14";
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat May 14 00:00:00 BOT 2014
setDate(date); //Set date in bean

前端(在值内引用 bean 中的该字段):

<h:outputText value="#{bean.date}">
   <f:convertDateTime pattern="dd.MM.yyyy" timeZone="EST" type="date" />
</h:outputText>

还没有测试它或任何东西......那是你正在寻找的吗?

文档

于 2014-05-14T18:04:30.093 回答