How do I initialise a Date field in a Grails domain object to act as a timestamp?

date, domain-object, grails

Solution

What you've written should work but you can use the GORM auto-timestamping feature by simply adding a field:

class Contact {
    Date dateCreated
}

If you want to keep your own names for the fields the same grails docs also show you how to use GORM events to set fields on save or update.

HTH

Problem

I have a domain class which has two dates in it and I want one of them populated with the current time when a record is created for the object, like a create timestamp... ``` class Contact { Date initiatedDate Date acceptedDate } ``` Is it sufficient just to new a `Date` object on one of them and make the other nullable until such a time as I need to fill it, sort of like this... ``` class Contact { static constraints = { acceptedDate(nullable:true) } Date initiatedDate = new Date() Date acceptedDate } ``` I'm experimenting, but I would like to know whether this is the right way to go about it or whether there is something more Grailsy or GORMy I should do in, say, an `init` function or by tweaking the domain object definition to have one by default, like it does an `id` and `version`. Thanks

Original source