tags:

views:

50

answers:

3

Is there an easy way to get the number of months(over multiple years) that have passed between two dates in ruby?

A: 

You could provide some test cases, here's one try, not tested very much really:

def months_between d1, d2
  d1, d2 = d2, d1 if d1 > d2
  (d2.year - d1.year)*12 + d2.month - d1.month - (d2.day >= d1.day ? 0 : 1)
end
Mladen Jablanović
+1  A: 

I found this solution, it seems logical and seems to work.

one = Time.local(2001,2,28,0,0)
two = Time.local(2003,3,30,0,0)
months = (enddate.month - startdate.month) + 12 * (enddate.year - startdate.year)

Reference: http://blog.mindtonic.net/calculating-the-number-of-months-between-two-dates-in-ruby/

Jamie
Looks Good, thanks guys.
Hulihan Applications
A: 

This addresses the month edge cases.(i.e. Mar 15 2009 - Jan 12 2010)

def months_between( d1, d2)
  d1, d2 = d2, d1 if d1 > d2
  y, m, d = (d2.year  - d1.year), (d2.month - d1.month), (d2.day - d1.day)
  m=m-1 if d < 0
  y, m = (y-1), (m+12) if m < 0
  y*12 + m
end
KandadaBoggu