Foo.first = {id: 1, start:2000-01-01 07:00:00 UTC, end: 2000-01-01 12:00:00 UTC, total_hours_worked: nil}

end在这里用作示例。
我用Foot.timestart创建了end,因为我只需要小时/分钟。我以前从未用过时间对象,所以请忍受我。
我需要用startend得到总小时数和分钟数:
start = Foo.find(1).start
end = Foo.find(1).end
start + end #=> errors
start.to_i + end.to_i = 1893438000 #=> What's that?
distance_of_time_in_words(start.to_i + end.to_i) #=> "about 60 years" What?

我期望5:00:00。我知道5:00:00实际上意味着早上5点,但是上下文使用的是不同的。
我很少搜索this。我真的不想在rails/ruby的“should have baked in method”中使用更多的gems。
我的问题会找到我真正想要达到的目标的答案(得到一周的总工作时间):
Foo.pluck(:total_hours_worked).sum(&:to_d) #=> best way?

其中:total_hours_worked是一个字符串,只是为了使事情不那么复杂。

最佳答案

以下是获得所需格式的方法("5:00:00"):

# Monkeypatch Integer class to add a new method
class Integer
  def pretty_duration
    seconds = self % 60
    minutes = (self / 60) % 60
    hours   = self / (60 * 60)

    format('%02d:%02d:%02d', hours, minutes, seconds)
  end
end

# Get start and end time converted into integers
timestart = (Time.now - 5.hours).to_i
timeend   = Time.now.to_i

# Use pretty_duration method.
# P.S. Difference between time objects already gives you a number, but we need Integer
(timeend - timestart).pretty_duration
#=> "05:00:00"

此设置允许您不依赖rails视图帮助程序(distance_of_time_in_words),因为您可能需要将时间格式化到视图之外的某个位置。
我的问题会找到我真正想要达到的目标的答案
(获取一周的总工作小时数):
最好的方式?在哪里?
Foo.pluck(:total_hours_worked).sum(&:to_d)将是一个字符串,只是为了减少
复杂的。
最有效的方法(如果您将:total_hours_worked设置为正确格式的字符串)是将其相加,并在db级别上转换为十进制:
Foo.sum('total_hours_worked::decimal')

08-04 11:52