Reputation: 11303
Is there an easy way to get the number of months(over multiple years) that have passed between two dates in ruby?
Upvotes: 0
Views: 510
Reputation: 2265
I found this solution, it seems logical and seems to work.
startdate = Time.local(2001,2,28,0,0)
enddate = 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/
Upvotes: 3
Reputation: 64363
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
Upvotes: 0
Reputation: 44090
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
Upvotes: 0