Search code examples
grailsgrails-ormjodatimegrails-2.0

Grails databinding date format


I have a problem within a grails 2.3 application, when it comes to data binding and correct date formats.

I use a datepicker (jQuery ui) that provides a <input type="hidden" /> that holds the selected date in ISO_8601 format. It will post a value like this: 2015-08-14 to the controller. The form itself and the post result is correct.

I use this simplified model:

class Thing {

    DateTime lastUpdated

    static constraints = {
        lastUpdated nullable: true
    }
}


when I try to create an entity, I will face this error message:

Invalid format: "2015-08-14" is malformed at "15-08-14"


A first research lead me to this change in the Config.groovy:

jodatime.format.html5 = true

(Link 3 in the list below)

Appying this leads to change. Now the error message is:

Invalid format: "2015-08-14" is too short (flip table)


Another try was to change the databinding.dateFormats to this (also in the Config.groovy):

grails.databinding.dateFormats = [ "yyyy-MM-dd HH:mm:ss.S","yyyy-MM-dd'T'hh:mm:ss'Z'", "yyyy-MM-dd"]

Which has no effect what so ever.


For my understanding a given date format should automatically be marshaled in a dateTime object. What configuration did I miss?


Here are relative question, that sadly did not help me:


Solution

  • You should add next line in config.groovy

    jodatime { format.org.joda.time.DateTime = "yyyy-MM-dd" }  
    

    But if you don't need time in this field, it's better to use LocalDate instead of DateTime here.

    class Thing {  
       LocalDate lastUpdated;
    

    ...

    jodatime {   
       format.org.joda.time.DateTime = "yyyy-MM-dd HH:mm:ss" 
       format.org.joda.time.LocalDate = "yyyy-MM-dd" 
    }  
    

    So you will use DateTime where you need date with time and LocalDate where date is enough