rAJ rAJ - 3 months ago 403
Groovy Question

Increment 1 hour on current time using Groovy

I am trying to increment only hour on current time.
E.g : User current time is

2017/08/28 17:27:23

Result i want is
Mon Aug 28 18:00:00 IST 2017

Means it only increment the hour and rest minutes and seconds should be zero.

def d = (new Date()).format('yyyy/MM/dd HH:mm:ss')
log.info d
use(groovy.time.TimeCategory) {
//Add increment hour by 1
def incre = new Date(d) + 1.hours
log.info incre
}


Result i am getting :
Mon Aug 28 18:35:24 IST 2017

Answer Source

You can use Date.set(Map map) to update specific fields like minute or second. Keep in mind that this method mutates Date object and returns void so in your case you can simply add:

incre.set(minute: 0, second: 0)

after initializing Date incre object and it will set minutes and seconds to 0, e.g.

def d = (new Date()).format('yyyy/MM/dd HH:mm:ss')
log.info d
use(groovy.time.TimeCategory) {
    //Add increment hour by 1
    def incre = new Date(d) + 1.hours
    incre.set(minute: 0, second: 0)
    log.info incre
}

Hope it helps.