Calculating the number of months between dates

How would you rate the number of months between two arbitrary dates? Given that even if 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 about sharing the timestamp difference with 2592000 (average number of seconds per month), but it seems hacked and error prone. And I would like to save it as quickly as possible (you need to run it thousands of times faster), so, I suppose, the use is strtotimealso not optimal?

+3
source share
2 answers

, "2" 31 1 , , , .

(psuedocode):

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

return (monthno2 - monthno1) + 1;

, - .

+7

, :

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;
}

:

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

Source: https://habr.com/ru/post/1759469/


All Articles