How do I calculate the difference of two dates in months? Also, incase it makes a difference, I am working with Date objects, not DateTime. Also, some rounding options might be nice so I can control if I want to round up or down on partial months.
Thanks!
Subtracting one Date or DateTime from another will yield the number of days as a fraction, but this can be evaluated as a Float
or Fixnum
as required.
For instance:
(Date.today - Date.today.advance(:months => -3)).to_f
# => 89.0
There were 89.0 days between today and the same calendar date three months ago. If you work this using 30-day months, or 30.4375 as they are on average, you end up with 2.92 months elapsed between then and now, or rounded up to the nearest integer, 3.
If you want to compute the precise number of calendar months, that is trickier, but can be done.
Something like this is more readable than figuring out seconds, and will give you the actual calendar difference:
# Calculate differnce between two dates in months
# Produces b - a
def month_difference(a, b)
difference = 0.0
if a.year != b.year
difference += 12 * (b.year - a.year)
end
difference + b.month - a.month
end
If you need to work out the difference based on days as well, you can just follow the pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With