0

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

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

我想以秒为单位获得时间间隔,time_beforetime_after在不同时间分配。任何人请指导我的方式。

4

2 回答 2

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
于 2012-12-30T05:00:14.510 回答
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}
于 2012-12-30T05:32:35.507 回答