Vivek Buddhadev
Vivek Buddhadev

Reputation: 397

Grails How to use Date.ClearTime() without affect on Domain Object Value

I'm trying to get date without time using following code.

List<Person> personList = Person.createCriteria().list(){
    eq("deleted", false)
    order("datetime","desc")
}

def dateTimeSet = new HashSet()

personList.each { personInstance ->

    Date originalDate = personInstance?.datetime

    println("Before Date In Instance: "+personInstance?.datetime)

    if(!dateTimeSet.contains(originalDate?.clearTime())){
        dateTimeSet.add(originalDate?.clearTime())
    }

    println("After Date In Instance: "+personInstance?.datetime)

}

OUTPUT:

Before Date In Instance: Thu Sep 20 18:34:11 IST 2018
After Date In Instance: Thu Sep 20 00:00:00 IST 2018

How the personInstance gets updated when I'm using clearTime() in originalDate object.

Let me know how to use clearTime() here without change in domain instance.

Upvotes: 0

Views: 408

Answers (1)

injecteer
injecteer

Reputation: 20699

As Date.clearTime() modifies the underlying instance, you should be creating a copy of it:

Date originalDate = personInstance?.datetime
if( !originalDate ) return
Date date = new Date( originalDate.time ).clearTime()
dateTimeSet << date

Upvotes: 3

Related Questions