Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of months between two Dates in Ruby on Rails

I have two Ruby on Rails DateTime objects. How to find the number of months between them? (Keeping in mind they might belong to different years)

like image 460
phoenixwizard Avatar asked Feb 24 '12 09:02

phoenixwizard


2 Answers

(date2.year * 12 + date2.month) - (date1.year * 12 + date1.month) 

more info at http://www.ruby-forum.com/topic/72120

like image 102
Massimiliano Peluso Avatar answered Oct 10 '22 15:10

Massimiliano Peluso


A more accurate answer would consider days in the distance.

For example, if you consider that the month-distance from 28/4/2000 and 1/5/2000 is 0 rather than 1, then you can use:

(date2.year - date1.year) * 12 + date2.month - date1.month - (date2.day >= date1.day ? 0 : 1) 
like image 35
dgilperez Avatar answered Oct 10 '22 16:10

dgilperez