两次之间的差异

时间:2014-10-17 11:09:53

标签: ruby

如何计算红宝石中两次之间的差异?

例如:

我有这个时间作为字符串

time1 = '08:00'
time2 = '12:00'

让我们考虑时间1是积极的,时间2是负数(想像工作小时,我一天工作8小时,另一天我错过12小时),我想做这样的事情:

diff = Time.parse(time1) - Time.parse(time2)
Time.at(diff).gmtime.strftime('%H:%M')
# expect to get something like "-04:00"
# but the result is  "20:00"

1 个答案:

答案 0 :(得分:1)

要了解您的代码有什么问题,让我们逐个执行:

▶ Time.parse('08:00') - Time.parse('12:00')
# => -14400.0

秒,呵呵。细

▶ Time.at(Time.parse('08:00') - Time.parse('12:00'))
=> 1969-12-31 21:00:00 +0100

哇。所以,Time.at不是我们梦想的方法。此外,我不知道在标准库中从格式%H:%M获取数小时的方式。但是:

▶ sprintf "%+03i:%02i", -14400 / 3600, -14400 / 60 % 60 # hours, minutes
# => "-04:00"

唯一的问题仍然是一个迹象。总结:

▶ time1 = '06:28'; time2 = '12:00'
▶ diff = Time.parse(time1) - Time.parse(time2)
▶ sprintf "%+03i:%02i", (diff / diff.abs) * (diff.abs / 3600), diff.abs / 60 % 60
# => "-05:32"

希望它有所帮助。

对于那些喜欢monkeypatching的人来说,

UPD:

class Time
  def diff_hours other
    return nil unless Time === other
    diff = self - other
    sprintf "%+03i:%02i", (diff / diff.abs) * (diff.abs / 3600), diff.abs / 60 % 60
  end  
end  
# => :diff_hours
▶ Time.parse('06:32').diff_hours Time.parse('12:00')
# => "-05:28"