If I understood well, you are looking for something like this:
require 'date'
def last_day_of_month(date)
(((date - date.day + 1) >> 1) - 1).day
end
def diff_in_months(date1, date2, precision=1)
if date2 < date1
return -diff_in_months(date2, date1, precision)
end
days_month_1 = last_day_of_month(date1)
ratio1 = (days_month_1 - date1.day + 1) / days_month_1.to_f
days_month_2 = last_day_of_month(date2)
ratio2 = date2.day / days_month_2.to_f
months_diff = (date2.year - date1.year) * 12 +
date2.month - date1.month - 1
(ratio1 + ratio2 + months_diff).round(precision)
end
date1 = Date.new(2015, 1, 1)
date2 = Date.new(2015, 2, 14)
date3 = Date.new(2015, 3, 14)
date4 = Date.new(2015, 4, 1)
date5 = Date.new(2016, 1, 1)
date6 = Date.new(2016, 2, 14)
diff_in_months(date1, date2) # 1.5
diff_in_months(date2, date1, 2) # -1.5
diff_in_months(date1, date3, 2) # 2.45
diff_in_months(date4, date4, 2) # 0.03 (1 day in 30)
diff_in_months(date5, date6, 2) # 1.48 (Feb'16 has 29 days)
1.month
? – Reinstate Monica -- notmaynard