The way to calculate time duration in groovy is with TimeDuration:
import groovy.time.TimeCategory
import groovy.time.TimeDuration
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()}"
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()}"
outputs>> duration in days: 17741
duration = TimeCategory.minus(now, earlier)
println duration
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
}
Top comments (0)