【问题标题】:Ruby on Rails: calculate time differenceRuby on Rails:计算时差
【发布时间】:2017-03-06 17:21:37
【问题描述】:

我正在尝试计算我在 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 助手,它可以使所有这些都变得单行:)

感谢您阅读我。

【问题讨论】:

标签: ruby-on-rails time helper


【解决方案1】:

您可以尝试使用 Ruby 核心库中的 Time 类。使用Time.at(seconds) 创建一个新的 Time 对象,该对象具有自 Epoch 以来的给定秒数。由于您的时间窗口小于 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,因为这会降低剩余时间的准确性

【讨论】:

    【解决方案2】:

    嗯,你可以使用时差宝石

    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}
    

    【讨论】:

    • 感谢您的回答,但我不确定为这样的简单任务带来 Gem 是否真的比辅助方法更好:-/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多