Format Date output in JSF

JsfElDate Formatting

Jsf Problem Overview


If #{myBean.birthdate} is of java.util.Calendar or java.util.Date type, can I possibly format this inside the EL itself using an existing function perhaps, with the output of like the one produced by the DateFormat's SHORT, MEDIUM,LONG abd FULL output type?

Instead of outputting the complete form for the #{myBean.birthdate}: Wed Jan 19 19:01:42 WIT 2011, I just prefer a simple output of Jan 19, 2011.

Should I use #{formatBean.format(myBean.birthdate)} instead?

Jsf Solutions


Solution 1 - Jsf

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

Solution 2 - Jsf

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

Solution 3 - Jsf

With EL 2 (Expression Language 2) you can use this type of construct for your question:

    #{formatBean.format(myBean.birthdate)}

Or you can add an alternate getter in your bean resulting in

    #{myBean.birthdateString}

where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbert GanView Question on Stackoverflow
Solution 1 - JsfjmjView Answer on Stackoverflow
Solution 2 - JsfMartin HöllerView Answer on Stackoverflow
Solution 3 - JsfCorneil du PlessisView Answer on Stackoverflow