Ruby:计算两次之间的时间差 [英] Ruby: Calculate time difference between 2 times

查看:93
本文介绍了Ruby:计算两次之间的时间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算两次之间的差值.start_time: 22:00(Rails 将此解释为 2015-12-31 22:00:00 +0100)second_time: 02:00(Rails 将此解释为 2015-12-31 02:00:00 +0100).第二次是 4 小时后,所以在第二天.有没有办法计算这种差异?

I want to calculate the difference between 2 times. start_time: 22:00 (Rails interprets this as 2015-12-31 22:00:00 +0100) second_time: 02:00 (Rails interprets this as 2015-12-31 02:00:00 +0100). The second time is 4 hours later, so in the next day. Is there a way to calculate this difference?

我不能简单地这样做:second_time - first_time,因为这给了我 22 小时而不是 4 小时的差异.

I can not simply do this: second_time - first_time, because this gives me a difference of 22 hours instead of 4 hours.

一些背景信息:作业从 22:00 开始,到第二天 02:00 结束.因为我只填写了这份工作的表格次数,所以上面2个值的这个时间是2015-12-31 22:00:00 +0100和2015-12-31 02:00:00 +0100.我不希望用户填写包括日期在内的时间.真正的时间差应该是4小时.

Some background information: A job is starting at 22:00 and ending the next day at 02:00. Because i fill in the form of this job only times, this times for the above 2 values are 2015-12-31 22:00:00 +0100 and 2015-12-31 02:00:00 +0100. I don't want the user to fill in the time including the date. The real difference between the times should be 4 hours.

所以我真正想要的是计算 22:00 和 02:00(在第二天)之间的差异.

So what i actually want is calculate the difference between 22:00 and 02:00 (in the next day).

推荐答案

我不明白为什么你认为它应该返回 4 小时或为什么它返回 22 小时.对于您的示例,20 小时是正确的:

I don't understand why you think it should return 4 hours or why it does return 22 hours. 20 hours would be correct for your example:

require 'time'

a = Time.parse('2015-12-31 22:00:00 +0100')
b = Time.parse('2015-12-31 02:00:00 +0100')

a - b
#=> 72000.0 # difference in seconds

(a - b) / 3600
#=> 20.0  # difference in hours

<小时>

更新:您似乎只处理时间部分,而不处理实际日期.我假设您必须处理的最大差异是 24 小时:


Update: It seems like you are dealing only with the time portion and not with the actual date. And I assume the maximum difference you will have to deal with is 24 hours:

def time_difference(time_a, time_b)
  difference = time_b - time_a

  if difference > 0
    difference
  else
    24 * 3600 + difference 
  end
end

a = Time.parse('2015-12-31 22:00:00 +0100')
b = Time.parse('2015-12-31 02:00:00 +0100')
time_difference(a, b) / 3600
# => 4 # hours

a = Time.parse('2015-12-31 02:00:00 +0100')
b = Time.parse('2015-12-31 22:00:00 +0100')
time_difference(a, b) / 3600
# => 20 # hours

这篇关于Ruby:计算两次之间的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆