问题
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.
回答1:
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
回答2:
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*/ }
回答3:
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
来源:https://stackoverflow.com/questions/3909855/groovy-time-durations