Time difference in hours

RubyTime

Ruby Problem Overview


I am trying to get the difference in hours for two different Time instances. I get these values from the DB as a :datetime column

How can I do this so that it includes the months and years as well in the calculation while ignoring or rounding the minutes? Can this only be done manually or is there a function to do this?

Ruby Solutions


Solution 1 - Ruby

((date_2 - date_1) / 3600).round

or

((date_2 - date_1) / 1.hour).round

Solution 2 - Ruby

Try Time Difference gem for Ruby at https://rubygems.org/gems/time_difference

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_years

Solution 3 - Ruby

this works great, example for number of hours since user created account

(Time.parse(DateTime.now.to_s) - Time.parse(current_user.created_at.to_s))/3600

Solution 4 - Ruby

You can use a gem called time_diff to get the time difference in very useful formats

Solution 5 - Ruby

You can use a Rails' method distance_of_time_in_words

distance_of_time_in_words(starting_time, ending_time, options = {include_seconds: true })

Solution 6 - Ruby

In Rails, there is now a far more natural way to achieve this:

> past = Time.now.beginning_of_year
2018-01-01 00:00:00 +0100

> (Time.now - past) / 1.day
219.50031326506948

Solution 7 - Ruby

in_hours (Rails 6.1+)

Rails 6.1 introduces new ActiveSupport::Duration conversion methods like in_seconds, in_minutes, in_hours, in_days, in_weeks, in_months, and in_years.

As a result, now, your problem can be solved as:

date_1 = Time.parse('2020-10-19 00:00:00 UTC')
date_2 = Time.parse('2020-10-19 03:35:38 UTC') 

(date_2 - date_1).seconds.in_hours.to_i
# => 3

Here is a link to the corresponding PR.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstellardView Question on Stackoverflow
Solution 1 - RubyRômulo CecconView Answer on Stackoverflow
Solution 2 - Rubyuser2295540View Answer on Stackoverflow
Solution 3 - RubyDino ReicView Answer on Stackoverflow
Solution 4 - RubyAbhilash M AView Answer on Stackoverflow
Solution 5 - RubyThe Whiz of OzView Answer on Stackoverflow
Solution 6 - RubyMatthias WinkelmannView Answer on Stackoverflow
Solution 7 - RubyMarian13View Answer on Stackoverflow