Skip to main content

JSF Tip #52 - How to convert a date in JSF

Posted by mriem on December 6, 2013 at 9:35 AM PST

How do you convert a date in JSF?

The example below outputs the date using the long date style

<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>f:convertDateTime dateStyle demo</title>
    </h:head>
    <h:body>
        <h1>f:convertDateTime dateStyle demo</h1>
        <p>
            The date below is rendered using dateStyle="long" and type="date".
        </p>
        <h:form>
            <h:outputText value="#{dateTimeConverterBean.date}">
                <f:convertDateTime dateStyle="long" type="date"/>
            </h:outputText>
        </h:form>
        <p>
            <a href="index.xhtml">Up</a>
        </p>
    </h:body>
</html>

If you need it to be a specific locale the example below adds using the locale attribute.

<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>f:convertDateTime dateStyle and locale demo</title>
    </h:head>
    <h:body>
        <h1>f:convertDateTime dateStyle and locale demo</h1>
        <p>
            The date below is rendered using dateStyle="long", locale="es" and
            type="date".
        </p>
        <h:form>
            <h:outputText value="#{dateTimeConverterBean.date}">
                <f:convertDateTime dateStyle="long" locale="es" type="date"/>
            </h:outputText>
        </h:form>
        <p>
            <a href="index.xhtml">Up</a>
        </p>
    </h:body>
</html>

Note the code for this sample is available as part of the Glassfish samples (see the subversion repository at https://svn.java.net/svn/glassfish-samples~svn/trunk/ws/javaee7/jsf/dateTimeConverter/)

And that is it.

Enjoy!

Related Topics >>