How to recover an interval of months between two dates?

Asked

Viewed 60 times

1

public function getMesesAtraso()
    {
        $data_debito= date_create($this->data_debito);
        return date_diff(date_create(now('m')), $data_debito)->format('%m');
    }

Returns only months in 2019

1 answer

3


You can’t compare months directly in different years because php rounds the value. For example, if the difference is 13 months, it will generate 1 year and 1 month. So when you filter through format it will bring unexpected information. I have created an alternative that I will explain next, see:

$data1 = new DateTime("2019-07-26");
$data2 = new DateTime("2020-08-26");

$diff = $data1->diff($data2); // comparação
$meses = $diff->y * 12 + $diff->m; // quantidade de meses final

echo  $meses;

In this small script I make the comparison, then I multiply by 12 the amount of years difference and sum with the amount of months.

The result will be exactly 13 months.

  • 1

    I wouldn’t say "dumb," they’re just different ways of counting time. Because there are other calendars currently in use that divide the year by 13 months: http://www.ethiopiantreasures.co.uk/pages/calendar.htm. - anyway, there is +1 :)

  • 1

    @hkotsubo you are right! There was not even imagined it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.