## Calculating time difference in months as a decimal number

There’s a number of functions out there for calculating the length of time in months but they only provide integer results. MySQL can do it too, for instance. But what if you need to get a precise number?

2008-11-15 minus 2008-10-01 can’t be one if you’re calculating rent. It must be 1.466…

1. function monthCount(\$start, \$end) {
2.   list(\$startYear, \$startMonth, \$startDay) = split(‘-‘, \$start);
3.   list(\$endYear, \$endMonth, \$endDay) = split(‘-‘, \$end);
4.
5.   \$startMonthCount =
6.     (\$startYear * 12) +
7.     // number of months since the beginning of our calendar
8.     \$startMonth +
9.     // month number
10.     ( (\$startDay1) / date("t", strtotime(\$start)));
11.     // day number divided by the number of days in that month
12.
13.   \$endMonthCount = (\$endYear * 12) + \$endMonth +
14.     ( (\$endDay1) / date("t", strtotime(\$end)));
15.
16.   return \$endMonthCount\$startMonthCount;
17. }

Note: end date is not inclusive.