ruby-on-railsdate

Duration between two dates in Ruby (Rails)


If I have a specific date and then add a duration to it resulting in another date

For example:

d1 = Date.parse('1996-02-17')
d2 = d1 + 67.years + 3.months # 2063-05-17

Then, how can I get the difference between those dates back (in years and months in this case), because if I do something like

ActiveSupport::Duration.build(d2.to_time - d1.to_time)

then it produces 67 years, 2 months, 4 weeks, 20 hours, 5 minutes, and 24.0 seconds. I could try rounding it off etc, but that seems messy.

I don't necessarily have to use Duration for this. Is there any way to add/subtract spans of time in Ruby on Rails in such a way that the addition and subtraction are each other's inverse?


Solution

  • I initially accepted Nitesh's answer, but found that it was buggy in other instances, e.g. for dates

    d1 = Date.parse('1996-02-17')
    d2 = Date.parse('2063-05-16')
    

    which should be one day short of 67 years and 3 months, and therefore 67 years and 2 months.

    To fix it, also take the days into account:

    d1 = Date.parse('1996-02-17')
    d2 = d1 + 67.years + 3.months - 1.days
    
    years = d2.year - d1.year
    months = d2.month - d1.month
    days = d2.day - d1.day
    
    # Adjust if d2's month is before d1's month
    if months < 0
      years -= 1
      months += 12
    end
    
    months -= 1 if days < 0
    
    puts "#{years} years and #{months} months"