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 inclu
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.
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
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
You can use a Rails' method distance_of_time_in_words
distance_of_time_in_words(starting_time, ending_time, options = {include_seconds: true })
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
((date_2 - date_1) / 3600).round
or
((date_2 - date_1) / 1.hour).round