Ruby-on-rails 计算两个 Time 对象之间的时间差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6784527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:38:44  来源:igfitidea点击:

Calculating difference in time between two Time objects

ruby-on-railsrubytime

提问by keruilin

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 类。我发现很难相信我需要扩展它,但我似乎无法找到一种本地方法来处理使用不同时间单位计算经过的时间。

回答by Stephen Provis

This should work:

这应该有效:

hours = ((created - updated) / 1.hour).round

Related question: Rails Time difference in hours

相关问题:Rails 时差(以小时为单位)

回答by Samuel - innovega

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 :)

希望对你有帮助 :)

回答by nugget

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_coercion。它比较两次并以秒为单位返回结果。

hours=(created.minus_with_coercion(updated)/3600).round