bind date to command object in Grails

If you're using Grails 2.3 or later, you can add multiple custom date formats for data binding in your Config.groovy

grails.databinding.dateFormats = ["MM/dd/yyyy"]

Then when Grails attempts to bind the request parameters to Command object properties, your custom format will be tried when parsing the date String in the request parameters eg.

class MyController {
    def myAction(MyCommandObject cmd) {
        println cmd.date
        println cmd.date.class
    }
}

class MyCommandObject {
    Date date
}

then when you hit eg.

http://localhost:8080/myController/myAction?date=12/13/2013

you should see something like ->

Fri Dec 13 00:00:00 EST 2013
class java.util.Date

on your console.


Co-incidentally I was looking at the same problem today, and followed this answer from @Don. I was able to bind a date properly to the command object.

@Validateable
class BookCommand {
    String name
    Date pubDate
    Integer pages
}

//Controller
def index(BookCommand cmd) {
        println cmd.name
        println cmd.pages
        println cmd.pubDate

        render "Done"
    }

//src/groovy
class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        String dateFormat = 'yyyy/MM/dd'
        registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true))
    }
}

//URL
http://localhost:8080/poc_commandObject/book?name=Test&pages=10&pubDate=2012/11/11

//Println
Test
10
Sun Nov 11 00:00:00 EST 2012

Worked for me if using the correct @BindingFormat. Example:

import grails.databinding.BindingFormat
class DateRangeFilter {
    String fieldName
    @BindingFormat('yyyy-MM-dd')
    Date from
    @BindingFormat('yyyy-MM-dd')
    Date to 
}