tags:

views:

25

answers:

2

Hi,

How would you go about calculating the amount of months between two arbitrary dates? Given that even if just one day falls on a month, it is considered a full month.

Examples:

  • 2010-01-01 - 2010-03-31 = three months
  • 2010-06-15 - 2010-09-01 = four months

Et cetera. I thought of just dividing the difference of timestamps with 2592000 (average number of seconds in a month) but that seems hacky and prone to errors. And I'd like to keep it as fast as possible (needs to run thousands of times quick), so I guess using strtotime isn't optimal either?

+2  A: 

If I am reading your question correctly, you would want to return "2" for January 31st and February 1st, because it spans both January and February, even though they are only 1 day apart.

You could work out (psuedocode):

monthno1 = (date1_year * 12) + date1_month;
monthno2 = (date2_year * 12) + date2_month;

return (monthno2 - monthno1) + 1;

This assumes that the second date is the later date.

thomasrutter
Yup, this seems to do it properly, thanks!
Tatu Ulmanen
A: 

Assuming the dates are in a known format:

function getMonths($start, $end) {
    $startParsed = date_parse_from_format('Y-m-d', $start);
    $startMonth = $startParsed['month'];
    $startYear = $startParsed['year'];

    $endParsed = date_parse_from_format('Y-m-d', $end);
    $endMonth = $endParsed['month'];
    $endYear = $endParsed['year'];

    return ($endYear - $startYear) * 12 + ($endMonth - $startMonth) + 1;
}

This gives:

print(getMonths('2010-01-01', '2010-03-31')); // 3
print(getMonths('2010-06-15', '2010-09-01')); // 4
Edward Mazur