嗨,我正在尝试计算Groovy中两次之间的差异(持续时间)。例如
start = "2010-10-07T22:15:33.110+01:00"
stop = "2010-10-07T22:19:52.356+01:00"
理想情况下,我希望获得以小时,分钟,秒,毫秒为单位返回的持续时间。
任何人都可以帮忙。我尝试使用Groovy的工期类,但未能取得任何进展。
感谢您的协助。
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
如果您特别需要使用上面字符串中提供的日期。尝试此操作,首先它们的格式有点奇怪,尤其是+01:00(这是时区),我希望它是+0100才能起作用。您可以删除我刚刚进行替换的时区。
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
输出
Thu Oct 07 15:15:33 MDT 2010 Thu Oct 07 15:19:52 MDT 2010 4 minutes, 19.246 seconds
def elapsedTime(Closure closure){
def timeStart = new Date()
closure()
def timeStop = new Date()
TimeCategory.minus(timeStop, timeStart)
}
然后
TimeDuration timeDuration = elapsedTime { /*code you want to time*/ }
start
或stop
的任何值一起使用,因此我分享了这一点。 Demian答案的改进,以供将来参考。它仅使用OP变量,并使用正则表达式进行通用替换,以保留时区偏移量的值
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