TL; DR:我需要将
HH:MM:SS.ms
和HH:MM:SS.ms
之间的差异视为HH:MM:SS:ms
这是一个棘手的问题。我正在尝试计算两个时间戳之间的差异,如下所示:
In: 00:00:10.520
Out: 00:00:23.720
应该提供:
Diff: 00:00:13.200
我以为我会将时间解析为实际的Time
个对象并使用其中的差异。这在前一种情况下效果很好,并返回00:0:13.200
。
然而,对于某些人来说,这不起作用,因为Ruby使用usec
而不是msec
:
In: 00:2:22.760
Out: 00:2:31.520
Diff: 00:0:8.999760
显然,差异应该是00:00:8:760
而不是00:00:8.999760
。 我真的很想tdiff.usec.to_s.gsub('999','')
......
这是我的代码到目前为止(这些是从输入字符串解析,如“0:00:10:520”)。
tin_first, tin_second = ins.split(".")
tin_hours, tin_minutes, tin_seconds = tin_first.split(":")
tin_usec = tin_second * 1000
tin = Time.gm(0, 1, 1, tin_hours, tin_minutes, tin_seconds, tin_usec)
tout
也是如此。然后:
tdiff = Time.at(tout-tin)
对于输出,我使用:
"00:#{tdiff.min}:#{tdiff.sec}.#{tdiff.usec}"
有没有更快的方法呢?记住,我只想要两次之间的区别。我错过了什么?
我目前正在使用Ruby 1.9.3p6。
答案 0 :(得分:5)
使用Time
:
require 'time' # Needed for Time.parse
def time_diff(time1_str, time2_str)
t = Time.at( Time.parse(time2_str) - Time.parse(time1_str) )
(t - t.gmt_offset).strftime("%H:%M:%S.%L")
end
out_time = "00:00:24.240"
in_time = "00:00:14.520"
p time_diff(in_time, out_time)
#=> "00:00:09.720"
这是一个不依赖于Time
的解决方案:
def slhck_diff( t1, t2 )
ms_to_time( time_as_ms(t2) - time_as_ms(t1) )
end
# Converts "00:2:22.760" to 142760
def time_as_ms( time_str )
re = /(\d+):(\d+):(\d+)(?:\.(\d+))?/
parts = time_str.match(re).to_a.map(&:to_i)
parts[4]+(parts[3]+(parts[2]+parts[1]*60)*60)*1000
end
# Converts 142760 to "00:02:22.760"
def ms_to_time(ms)
m = ms.floor / 60000
"%02i:%02i:%06.3f" % [ m/60, m%60, ms/1000.0 % 60 ]
end
t1 = "00:00:10.520"
t2 = "01:00:23.720"
p slhck_diff(t1,t2)
#=> "01:00:13.200"
t1 = "00:2:22.760"
t2 = "00:2:31.520"
p slhck_diff(t1,t2)
#=> "00:00:08.760"
答案 1 :(得分:1)
我认为以下方法可行:
out_time = "00:00:24.240"
in_time = "00:00:14.520"
diff = Time.parse(out_time) - Time.parse(in_time)
Time.at(diff).strftime("%H:%M:%S.%L")
# => "01:00:09.720"
它 打印01
一小时,我真的不明白。
与此同时,我使用了:
Time.at(diff).strftime("00:%M:%S.%L")
# => "00:00:09.720"
当然,任何做得更好的答案都会得到一个upvote或者接受。
答案 2 :(得分:0)
in_time = "00:02:22.760"
out_time = "00:02:31.520"
diff = (Time.parse(out_time) - Time.parse(in_time))*1000
puts diff
输出:
8760.0 millliseconds
Time.parse(out_time) - Time.parse(in_time)
在seconds
中得出结果,因此乘以1000
转换为milliseconds
。