Subtract dates in Ruby and get the difference in minutes
48,890
Solution 1
(time1 - time2) / 60
If the time objects are string, Time.parse(time)
them first
Solution 2
If you subtract two Date or DateTime objects, the result is a Rational representing the number of days between them. What you need is:
a = Date.new(2009, 10, 13) - Date.new(2009, 10, 11)
(a * 24 * 60).to_i # 2880 minutes
or
a = DateTime.new(2009, 10, 13, 12, 0, 0) - DateTime.new(2009, 10, 11, 0, 0, 0)
(a * 24 * 60).to_i # 3600 minutes
Solution 3
https://rubygems.org/gems/time_difference - Time Difference gem for Ruby
start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_minutes
Related videos on Youtube
Author by
Mark
Updated on May 18, 2020Comments
-
Mark about 4 years
how do i subtract two different UTC dates in Ruby and then get the difference in minutes?
Thanks
-
Ephemera over 11 yearsNot sure if it may have changed between versions (Chubas's answer is common around the Internet), but as of version 1.9.3p364 this is the correct answer.
-
Alex Korban over 11 yearsI think my answer has been correct since before 1.9.3 was released :)
-
Tyler Rick about 11 yearsDepends if the objects in question are Time objects or Date objects. Time#- returns the number of seconds, while Date#- returns the number of days.
-
utiq over 8 yearsTimeDifference gem is a great solution
-
Aleks about 7 yearsThe second part of the answer is not correct.
DateTime
returns number of seconds, and the accepted answer should be applied in that case - meaning(DateTime.new - DateTime.new)/60
-
Alex Korban about 7 yearsMy answer is correct as of Ruby 2.1. I haven't tried newer versions.
-
lafeber over 3 yearsAlmost the same but
(time1 - time2) / 1.minute
might be more readable.