keruilin
keruilin

Reputation: 17512

Calculating difference in time between two Time objects

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.

Upvotes: 17

Views: 23576

Answers (3)

Samuel Vega
Samuel Vega

Reputation: 181

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

Upvotes: 14

Stephen Provis
Stephen Provis

Reputation: 582

This should work:

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

Related question: Rails Time difference in hours

Upvotes: 46

nugget
nugget

Reputation: 168

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

Upvotes: 11

Related Questions