开发者

Calculating amount of months between dates

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
开发者_StackOverflow

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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜