Let's say I create two time objects from my user model:
假设我从我的用户模型中创建了两个时间对象:
created = u.created_at
updated = u.updated_at
How do I calculate the difference in terms of hours between the two time objects?
如何计算两个时间对象之间的小时差?
hours = created - updated
I'd like to wrap this in a method and extend the Time class. I find it hard to believe I'd need to extend it, but I can't seem to find a native method that handles calculating elapsed time using different time units.
我想把它封装在一个方法中并扩展Time类。我发现很难相信我需要扩展它,但是我似乎找不到一个本机方法来使用不同的时间单元来处理计算消耗时间。
3 个解决方案
#1
36
This should work:
这应该工作:
hours = ((created - updated) / 1.hour).round
Related question: Rails Time difference in hours
相关问题:Rails的时间差异在几个小时内。
#2
12
Another option would be to use distance_of_time_in_words helper:
另一个选择是使用distance_of_time_in_words助手:
<%= distance_of_time_in_words u.created_at, u.updated_at %>
I hope you find it useful :)
我希望你觉得它有用:
#3
10
I would like to add an alternate answer using a rails-specific method. The Time class has a method called minus_with_coercion. It compares two times and returns a result in seconds.
我想使用特定于rails的方法添加另一个答案。Time类有一个名为minus_with_mandatory的方法。它比较两次,并在几秒钟内返回结果。
hours=(created.minus_with_coercion(updated)/3600).round
#1
36
This should work:
这应该工作:
hours = ((created - updated) / 1.hour).round
Related question: Rails Time difference in hours
相关问题:Rails的时间差异在几个小时内。
#2
12
Another option would be to use distance_of_time_in_words helper:
另一个选择是使用distance_of_time_in_words助手:
<%= distance_of_time_in_words u.created_at, u.updated_at %>
I hope you find it useful :)
我希望你觉得它有用:
#3
10
I would like to add an alternate answer using a rails-specific method. The Time class has a method called minus_with_coercion. It compares two times and returns a result in seconds.
我想使用特定于rails的方法添加另一个答案。Time类有一个名为minus_with_mandatory的方法。它比较两次,并在几秒钟内返回结果。
hours=(created.minus_with_coercion(updated)/3600).round