Groovy time durations

Viewed 45468

Hi I'm trying to calculate the difference (duration) between two times in Groovy. e.g.

start =  "2010-10-07T22:15:33.110+01:00"
stop =   "2010-10-07T22:19:52.356+01:00"

Ideally I would like the get the duration returned in Hours, Minutes, Seconds, Milliseconds.

Can anybody please help. I've tried to use Groovy's duration classes but have not been able to make any progress.

Thanks for your assistance.

3 Answers

I had the same question and I used what Demian suggested in his answer, except that I needed it to be generic and to work with any values of start or stop, hence I'm sharing this improvement of Demian's answer for future reference.

It just uses the OP variables, with a generic replacement using a regex, so as to keep the value of the time-zone offset

Note that groovy.time.TimeDuration is not serializable, and thus will mess up with the jenkins' CPS-groovy and throw java.io.NotSerializableException.

import groovy.time.*

def start =  "2010-10-07T22:15:33.110+01:00"
def stop =   "2010-10-07T22:19:52.356+01:00"
def format = "yyy-MM-dd'T'HH:mm:ss.SSSZ"
start = Date.parse(format , start.replaceAll(/([+\-])(\d\d):(\d\d)/, /$1$2$3/))
println start
stop = Date.parse(format , stop.replaceAll(/([+\-])(\d\d):(\d\d)/, /$1$2$3/))
println stop
TimeDuration duration = TimeCategory.minus(stop, start)
println duration
Related