计算 Rails 中的总小时数

Syl*_*lar 4 ruby postgresql ruby-on-rails ruby-on-rails-5

Foo.first = {id: 1, start:2000-01-01 07:00:00 UTC, end: 2000-01-01 12:00:00 UTC, total_hours_worked: nil}
Run Code Online (Sandbox Code Playgroud)

end这里作为一个例子。

我已经为两者创建Foo了,因为我只需要几小时/分钟。我以前从未使用过 Time 对象,所以请耐心等待。t.timestartend

我需要使用start和获取总小时数和分钟数end

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?
Run Code Online (Sandbox Code Playgroud)

我期待着5:00:00。我知道这5:00:00实际上意味着凌晨 5 点,但上下文会有所不同。

做了一些搜索我就看到了这个。我真的不想在 Rails/Ruby 中为这个“应该在方法中烘焙”使用更多的 gem。

我的问题将找到我真正想要实现的目标的答案(获取本周的工作总小时数):

Foo.pluck(:total_hours_worked).sum(&:to_d) #=> best way?
Run Code Online (Sandbox Code Playgroud)

哪里:total_hours_worked会有一个字符串,只是为了让事情变得不那么复杂。

And*_*eko 5

以下是获得所需格式的方法 ( "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"
Run Code Online (Sandbox Code Playgroud)

此设置允许您不依赖 Rails 视图助手 ( distance_of_time_in_words),因为您可能需要在视图之外的某个位置格式化时间。

我的问题将找到我真正想要实现的目标的答案(获取本周的工作总小时数):

Foo.pluck(:total_hours_worked).sum(&:to_d)#=> 最好的方法?哪里 :total_hours_worked会有一个字符串,只是为了让事情变得不那么复杂。

最有效的方法(如果您选择使用total_hours_worked正确格式的字符串)将在数据库级别将其总结为十进制:

Foo.sum('total_hours_worked::decimal')
Run Code Online (Sandbox Code Playgroud)