开发者

format date inside a select item [duplicate]

This question already has answers here: Format date in <f:selectItem(s) itemLabel> using DateTimeConverter (3 answers) Closed 7 years ago.

Is there a way to format the date object to be displayed in a select item ?

Here's my example :

<h:selectOneMenu 
    label="Period" 
    value="#{myBean.periodStartEndList}"
    id="periodStartEnd" 
    converter="genericConverter">

    <f:selectItem itemLabel="Choose one .." noSelectionOption="true" />

    <f:selectItems 
        value="#{myBean.periodStartEndList}" 
        var="periodStartEnd"
        itemValue="#{periodStartEnd}" 
        itemLabel="#{periodStartEnd.map['dateStart']} -- #{periodStartEnd.map['dateEnd']}" />
</h:selectOneMenu>

And the combo / selection displays these :

Sun May 01 14:57:21 WIT 2011 -- Thu May 05 14:57:21 WIT 2011
Fri May 06 14:57:21 WIT 2011 -- Tue May 10 14:57:21 WIT 2011

I would like to have something simpler like :

01-05-2011 -- 05-05-2011
06-0开发者_运维百科5-2011 -- 10-05-2011

I wonder how to achieve this ?

Thank you !


You create EL function for conversion and use it. Check http://www.javabeat.net/tips/4-expression-language-in-jsp-20.html and http://wiki.apache.org/myfaces/Parameters_In_EL_Functions. Disclaimer: I never used it and don't know if it works.


You'd need to employ a date formatter. AFAIK #{periodStartEnd.map['dateStart']} would end up in a toString() call assuming this returns a Date object.

I'm not sure whether Java EL in JSF 2.0 has built in function parameters already, but if not, you could use JBoss EL (extensions to Java EL). With that you could provide a formatter bean and use something like #{formatter.format(periodStartEnd.map['dateStart'], 'dd-MM-yyyy')}

The format would then create a SimpleDateFormat from the format string and return the formatted date as a string.

You could also pass in a locale in order to provide localized formats.

A third alterative would be to directly store the formatted strings in periodStartEnd and access them.


You can use f:convertDateTime and specify a pattern.


You can use a converter method in your bean, as:

public class MyBean{
    ...
        public String formatDate(Date fecha, String pattern) {
            return (new SimpleDateFormat(pattern)).format(fecha);
        }
    ...
}

And, in your xhtml page inside f:selectItems:

<f:selectItems 
    value="#{myBean.periodStartEndList}" 
    var="periodStartEnd"
    itemValue="#{periodStartEnd}" 
    itemLabel="#{myBean.formatDate(periodStartEnd.map['dateStart'],'dd-MM-yyyy')} -- #{myBean.formatDate(periodStartEnd.map['dateEnd'],'dd-MM-yyyy')}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜