Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails calculate date range in months

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!

like image 825
brettish Avatar asked May 04 '11 17:05

brettish


2 Answers

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.

like image 146
tadman Avatar answered Oct 31 '22 03:10

tadman


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

like image 32
Glenjamin Avatar answered Oct 31 '22 02:10

Glenjamin