从End_time(UTC)中减去Time.now给我一个浮点数(hhmmss.xx)。如何将其格式化为HH:MM以便我可以将它用于倒数计时器?

时间:2014-06-05 01:52:08

标签: ruby-on-rails ruby

我有一个end_time,我想为end_time.utc - Time.now创建一个计时器。但是,当我减去该值时,我得到一个像23510.29642这样的浮点数,我发现它代表小时,分钟,秒,后跟一段时间和毫秒。

end_time
=>  Wed, 04 Jun 2014 19:00:00 UTC +00:00 

end_time.utc - Time.now
=> -24614.329399 

如何格式化浮点数以便在不手动解析字符串的情况下得到-2:46

1 个答案:

答案 0 :(得分:2)

两个Time对象之间的差异返回两次之间的秒数。

e = Time.parse("Wed, 04 Jun 2014 19:00:00 UTC +00:00")
diff = e - Time.parse("Wed, 04 Jun 2014 21:49:00 UTC +00:00")

hours = (diff / 3600).to_i
minutes = (diff / 60).to_i % 60 # if e < Time.now then minutes = (diff / 60).to_i % 60 - 60
seconds = diff.to_i % 60 # same as minutes

puts hours # -2
puts minutes # -49
puts seconds # 0