Calculating difference in time between two Time ob

2019-01-23 04:41发布

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.

3条回答
Emotional °昔
2楼-- · 2019-01-23 05:30

This should work:

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

Related question: Rails Time difference in hours

查看更多
乱世女痞
3楼-- · 2019-01-23 05:31

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.

hours=(created.minus_with_coercion(updated)/3600).round
查看更多
Fickle 薄情
4楼-- · 2019-01-23 05:42

Another option would be to use distance_of_time_in_words helper:

<%= distance_of_time_in_words u.created_at, u.updated_at %>

I hope you find it useful :)

查看更多
登录 后发表回答