计算 Rails 中的总小时数

Calculate total hours in Rails

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为例

我已经为 startend 创建了 Foot.time,因为我只需要 hours/min。我以前从未使用过时间对象,所以请多多包涵。

我需要使用 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" 使用更多的宝石

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

Foo.pluck(:total_hours_worked).sum(&:to_d) #=> best way?

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

因为你需要在开始和结束之间有时间,所以你写的代码应该是:

distance_of_time_in_words(end.to_i - start.to_i)

您应该能够使用 here.

中描述的方法格式化输出

end是关键字。您不能为其赋值。

现在,获取时差:

start = "2000-01-01 07:00:00 UTC".to_time
endtime = "2000-01-01 12:00:00 UTC".to_time
difference = ((endtime - start) / 1.hour)
# => 5.0

或使用助手

distance_of_time_in_words(endtime, start)
# => "about 5 hours"

这里是你如何获得你想要的格式 ("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),因为您可能需要在视图之外的某个地方格式化时间。

My question will find an answer to what I'm really trying to achieve (get total of hours worked for the week):

Foo.pluck(:total_hours_worked).sum(&:to_d) #=> best way? Where :total_hours_worked would be a string, just to make things less complicated.

最有效的方法(如果您接受 total_hours_worked 作为正确格式的字符串)将其汇总并在数据库级别转换为十进制:

Foo.sum('total_hours_worked::decimal')

使用下面的代码来获取差异并以“5:00:00”的格式获取小时数

distance_of_time_in_words(end.to_i - start.to_i).strftime("%H%M%S")

t.strftime("%H:%M:%S") > "22:49:27"