Search code examples
dategrailsgroovynamed-query

Named query to show results by date (Year, month, day) in Grails 3.2.10


Given this domain:

class Burger{
  String description
  Date dateCreated
}

Currently, I have this namedQuery

queryOnDateCreated {Date dateArgument ->
        eq 'dateCreated', dateArgument
}

I need a query that allows me find all the objects in the domain Burger with a specific dateCreated only taking into accountYear, Month and day (of month), while ignoring hours, minutes, seconds, miliseconds.


Solution

  • After some additional research, I found a solution which I'm going to share in case it helps someone else:

    The named query needs to be as follows:

    queryOnDateCreated {Date dateArgument ->
        def dateArgumentIntervalEnd = DateUtils.addMilliseconds(dateArgument + 1, - 1)
        between 'dateCreated', dateArgument, dateArgumentIntervalEnd
    }
    

    Explanation:

    The "between" criteria returns every object in the domain whose date is between the interval given.

    Since dateArgument is a Date created only with Year, Month and Day, it's time should be 00:00:00:000 (the first moment of the day).

    Furthermore, "dateArgument + 1" holds the value of the next day (at the same time), which is why the substraction of 1 millisecond is required, that way "dateArgumentIntervalEnd" will hold the value of the same Year, Month and Day of "dateArgument" but the time will be 23:59:59:999 holding an interval of the whole day.