【问题标题】:Converting from one String reprensation of a Date to another in JSF在 JSF 中从一个日期的字符串表示形式转换为另一种表示形式
【发布时间】:2014-07-02 20:53:36
【问题描述】:

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

【问题讨论】:

  • 我试了一下。 :P

标签: jsf jsf-2 date-conversion converters


【解决方案1】:

后端(Bean):

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>

还没有测试它或任何东西......这就是你要找的吗?

Documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2020-11-21
    • 2015-01-26
    相关资源
    最近更新 更多