Ruby on Rails:计算时差

时间:2017-03-06 17:21:37

标签: ruby-on-rails time helper

我正在尝试计算Rails 5中记录的“剩余时间”。我的记录有一个created_at列(UTC)。

每条记录持续24小时,我的模型具有全局范围:

scope :available, -> { where(
  created_at: (Time.current - 24.hours)..Time.current
) }

现在,在前端,我需要的是:

Record id 1: 23:59:12
Record id 2: 22:23:03
...

经过一些研究,我发现有一些帮手正在做这项工作,但它看起来很难看,这就是我要求你帮助的原因。

这是我的(笨拙但有效)代码:

# In my helper:
def time_diff(start_time, end_time)
  seconds_diff = (start_time - end_time).to_i.abs

  hours = seconds_diff / 3600
  seconds_diff -= hours * 3600

  minutes = seconds_diff / 60
  seconds_diff -= minutes * 60

  seconds = seconds_diff

  "#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end

# And my the view:
time_diff(Time.current - 24.hours, model_instance.created_at)

我确定我错过了一些非常棒的Rails助手,它可以使所有这些单行:)

感谢您阅读。

2 个答案:

答案 0 :(得分:0)

好吧,你可以使用时差宝石

http://www.rubydoc.info/github/tmlee/time_difference

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_each_component
=> {:years=>1.0, :months=>12.0, :weeks=>52.14, :days=>365.0, :hours=>8760.0, :minutes=>525600.0, :seconds=>31536000.0}

答案 1 :(得分:0)

您可以尝试使用Ruby Core Library中的Time类。使用Time.at(seconds)创建一个具有自Epoch以来给定秒数的新Time对象。由于您的时间窗口不到24小时,您可以直接致电strftime而无需进行任何进一步的计算。

def time_diff(start_time, end_time)
 seconds_diff = (start_time - end_time).abs
 Time.at(seconds_diff).utc.strftime "%H:%M:%S"
end

您应该避免致电to_i,因为这会降低剩余时间的准确性

相关问题