Search

Dark theme | Light theme

February 18, 2011

Grails Goodness: Define Date Format in i18n ResourceBundle

The Grails formatDate tag supports the formatName attribute. The value of this property is the lookup key for the date format defined in the i18n properties files. So we can define a custom date format in grails-app/i18n/messages.properties and use it with the formatDate tag.

If we don't specify a value for the format and formatName attributes Grails will look for the keys date.format or default.date.format for a date format. If those keys cannot be found then the default pattern yyyy-MM-dd HH:mm:ss z' is used.

# File: grails-app/i18n/messages.properties
default.date.format=d/M/yyyy
custom.date.format=dd-MMM-yyyy
<%-- File: sample.gsp --%>

<g:set var="date" value="${new Date(111, 2, 21)}"/>

<g:formatDate date="${date}"/> outputs: 21/3/2011
<g:formatDate date="${date}" formatName="custom.date.format"/> outputs: 21-Mar-2011
<g:formatDate date="${date}" format="yyyy-MM-dd"/> outputs: 2011-03-21