jspjstljsp-tagsjstl-functions

JSTL fmt:formatDate with locale dependent pattern


In a JSP page I have to display some dates, but none of the available date formats (short, medium or long) suits me.

<fmt:formatDate value="${someDate}" type="date" dateStyle="short"/>
<fmt:formatDate value="${someDate}" type="date" dateStyle="medium"/>
<fmt:formatDate value="${someDate}" type="date" dateStyle="long"/>

I have to resort to a specified pattern:

<fmt:formatDate value="${someDate}" type="date" pattern="dd-MM/yyyy"/>

But, the pattern itself is locale dependent, I mean, I want to load the pattern from the message bundle. How can I do it?

I tried

<fmt:formatDate value="${someDate}" type="date" pattern="<fmt:message key='date.format.short'/>"/>

but it doesn't work.


Solution

  • You can use the <c:set> tag to store the value of the pattern.

    Something like this would do what you want:

    <c:set var="myPattern"><fmt:message key="date.format.short" /></c:set>
    
    <fmt:formatDate value="${someDate}" type="date" pattern="${myPattern}" />
    

    Or better yet, as pointed by @Sachin, use the var attribute:

    <fmt:message key="date.format.short" var="${myPattern}"/>
    
    <fmt:formatDate value="${someDate}" type="date" pattern="${myPattern}" />