您好,我正在计算Groovy中两次之间的差异(持续时间)。例如:
start = "2010-10-07T22:15:33.110+01:00"
stop = "2010-10-07T22:19:52.356+01:00"
理想情况下,我希望获取以小时、分钟、秒、毫秒为单位返回的持续时间。
有谁能帮帮忙。我尝试使用Groovy的duration类,但没有取得任何进展。
谢谢你的帮助。
发布于 2010-10-14 02:51:37
如果您只想找出创建自己的两次之间的差异(例如,查看执行某项任务需要多长时间),您可以使用:
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
发布于 2014-04-24 20:22:29
我会做这样的事
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*/ }
https://stackoverflow.com/questions/3909855
复制相似问题