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

  • The issue arises because when you subtract two Time objects, it returns the difference as an exact ActiveSupport::Duration, which accounts for the varying lengths of months, weeks, and days.

    If you want a simplified representation, like "67 years and 3 months", you can manually calculate the differences in years and months rather than relying on ActiveSupport::Duration.build.

    Here's a way to achieve your desired output:

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