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
Share:
48,890

Related videos on Youtube

Mark
Author by

Mark

Updated on May 18, 2020

Comments

  • Mark
    Mark about 4 years

    how do i subtract two different UTC dates in Ruby and then get the difference in minutes?

    Thanks

  • Ephemera
    Ephemera over 11 years
    Not 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
    Alex Korban over 11 years
    I think my answer has been correct since before 1.9.3 was released :)
  • Tyler Rick
    Tyler Rick about 11 years
    Depends 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
    utiq over 8 years
    TimeDifference gem is a great solution
  • Aleks
    Aleks about 7 years
    The 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
    Alex Korban about 7 years
    My answer is correct as of Ruby 2.1. I haven't tried newer versions.
  • lafeber
    lafeber over 3 years
    Almost the same but (time1 - time2) / 1.minute might be more readable.