DEV Community

ouryperd
ouryperd

Posted on

Passage of time calculations in Groovy

The way to calculate time duration in groovy is with TimeDuration:

import groovy.time.TimeCategory
import groovy.time.TimeDuration
Enter fullscreen mode Exit fullscreen mode

Short durations

Date timeStart = new Date()
sleep(randNum(10000))
Date timeStop = new Date()

TimeDuration durationShort = TimeCategory.minus(timeStop, timeStart)
println "duration: ${durationShort}"
println "duration in ms    : ${durationShort.toMilliseconds()}"
println "duration in millis: ${durationShort.getMillis()}"  //drops the seconds
println "duration in seconds: ${durationShort.getSeconds()}"
Enter fullscreen mode Exit fullscreen mode

outputs>>
duration: 9.911 seconds
duration in ms : 9911
duration in millis: 911
duration in seconds: 9

Date earlier = Date.parse('yyyy-MM-dd', "1974-08-11") //converts String to Date object
Date now = new Date()

TimeDuration durationLong = TimeCategory.minus(now, earlier)
println "duration in days: ${durationLong.getDays()}"
Enter fullscreen mode Exit fullscreen mode

outputs>> duration in days: 17741

duration = TimeCategory.minus(now, earlier)
println duration
Enter fullscreen mode Exit fullscreen mode

outputs>> 17741 days, 11 hours, 34 minutes, 5.824 seconds

The last two outputs will differ if you run it because time moves on.

This is just to get a random number of seconds, used in the first example:

def randNum(maxSize) {
    return Math.abs(new Random().nextInt() % maxSize) + 1 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)