I was reading a blog post titled Parse date in grails 2.x.x regardless format by Amit Pandey where he explained how we can parse dates automatically inside a controller. I realized that Grails 2.3.0 introduced a new annotation named as “BindingFormat” which can be used easily for binding string values to Date type.

Here is a quick example which explains the usage :

package com.jft

import org.grails.databinding.BindingFormat
class User {
    String username
    String password
    String fullName

    Date activationDate

Let’s say your form sends the value of activationDate in a textfield. User can enter value for date and it will be converted automatically in this format.

In case you want the conversion to happen automatically for all Date fields then you can specify the format in Config.groovy and it will be automatically picked up by Grails. In case the conversion fails then appropriate error will be thrown back to user. This is how you define the format in Config.groovy

grails.databinding.dateFormats = ['dd-MM-yyyy','MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S']

Now Grails will automtically try to convert date value in the formats specified in Config.groovy. The conversion will be tried in the specified order of formats.

NOTE : If the date field is using “BindingFormat” annotation then config values will not affect it’s behavior.