从格式化时间字符串获取时间间隔

时间:2012-12-30 04:52:54

标签: ruby

我有两个变量time_beforetime_after,如下所示:

time_before = Time.now.strftime("%H%M%S")
time_after = Time.now.strftime("%H%M%S")

我希望获得在不同时间分配的time_beforetime_after之间的时间间隔(以秒为单位)。有人请指导我。

2 个答案:

答案 0 :(得分:0)

time_before = Time.now
...
time_after = Time.now

puts "before #{time_before.strftime('%H%M%S')}"
puts "after #{time_before.strftime('%H%M%S')}"
puts "elapsed (seconds): #{time_after - time_before}" 
# its already in seconds, with fractional
puts "#{'%.0f' % (time_after - time_before)}" # just whole seconds

答案 1 :(得分:0)

time_before = Time.now.strftime("%H%M%S")
sleep(1)
time_after = Time.now.strftime("%H%M%S")

[time_before, time_after]
.map{|s| Time.parse(s.scan(/\d\d/).join(":"))}
.tap{|t1, t2| puts t2 - t1}