Groovy time durations
Asked Answered
S

5

42

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.

Samson answered 11/10, 2010 at 20:50 Comment(1)
is the format you got the times or did you convert to this format?Disembark
S
75

If you just want to find the difference between two times you create yourself (for instance to see how long something takes to execute) you could use:

import groovy.time.*

def timeStart = new Date()
// Some code you want to time
def timeStop = new Date()
TimeDuration duration = TimeCategory.minus(timeStop, timeStart)
println duration

If you specifically need to work with the dates as supplied as string above. Try this, first the format of them is a bit odd, in particular the +01:00, which is the timezone, I would expect it to be +0100 for format to work. You could just remove the timezone I just did a replace.

import groovy.time.*

def start = Date.parse("yyy-MM-dd'T'HH:mm:ss.SSSZ","2010-10-07T22:15:33.110+01:00".replace("+01:00","+0100"))
println start
def end = Date.parse("yyy-MM-dd'T'HH:mm:ss.SSSZ","2010-10-07T22:19:52.356+01:00".replace("+01:00","+0100"))
println end
TimeDuration duration = TimeCategory.minus(end, start)
println duration

Outputs

Thu Oct 07 15:15:33 MDT 2010
Thu Oct 07 15:19:52 MDT 2010
4 minutes, 19.246 seconds
Standoff answered 13/10, 2010 at 18:51 Comment(1)
Just a note TimeCategory is not thread safe. Found this out the hard wayTorrefy
S
25

I would do something like that

def elapsedTime(Closure closure){
    def timeStart = new Date()
    closure()
    def timeStop = new Date()
    TimeCategory.minus(timeStop, timeStart)
}

an then

TimeDuration timeDuration = elapsedTime { /*code you want to time*/ }
Salas answered 24/4, 2014 at 12:22 Comment(0)
L
1

Using the java.time.* packages

Suggested by groovy linters with the message 'Do not use java.util.Date. Prefer the classes in the java.time. packages'*

import java.time.Instant
import java.time.temporal.ChronoUnit

long elapsedTime(Closure closure) {
  Instant timeStart = Instant.now()
  closure()
  Instant timeStop = Instant.now()
  return ChronoUnit.MILLIS.between(timeStart, timeStop)
}

println elapsedInMillis = elapsedTime {
  // code you want to time, e.g.:
  sleep 456
}

More info: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

Lacking answered 29/10, 2022 at 20:7 Comment(0)
I
0

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
Iamb answered 5/11, 2019 at 10:17 Comment(0)
C
0

Sometimes you need to get duration for different "actions", are not in one flow, so you can't hold variables and you need to store it in any properties (even temp file): To get and store start time - SoapUI Groovy example:

    import groovy.time.*

//Define sysdate
TimeZone.setDefault(TimeZone.getTimeZone('EET'))
today = new Date()
def startDate = today.format("YYYY-MM-dd HH:mm:ss")

log.info(" Test execution start time: $startDate")

//Set start time itno test suite property
testRunner.testCase.testSuite.setPropertyValue("execStartTime",startDate.toString())

To get and store end time, and calculate the duration - SoapUI Groovy example:

    import groovy.time.*
//Define sysdate
TimeZone.setDefault(TimeZone.getTimeZone('EET'))
today = new Date()
def endDate = today.format("YYYY-MM-dd HH:mm:ss")

def end = Date.parse("YYYY-MM-dd HH:mm:ss",endDate)
log.info(" Test execution end time: $endDate")

//Set start end itno test suite property
testRunner.testCase.testSuite.setPropertyValue("execEndTime",end.toString())

//Calculate duration
def start = testRunner.testCase.testSuite.getPropertyValue("execStartTime")
def startDate = Date.parse("YYYY-MM-dd HH:mm:ss",start)
TimeDuration duration = TimeCategory.minus(end, startDate)

//Get out from 000
def durationText = duration.toString().replace(".000 seconds"," seconds")
log.info(" Test execution duration: $durationText")

//Set duration itno test suite property
testRunner.testCase.testSuite.setPropertyValue("execDuration",durationText.toString())

enter image description here

Croteau answered 16/11, 2023 at 17:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.