Count difference of months between dates

0

I took this example right here, it works, but it does not work the way I expected, I need to get the amount of months between the dates, but the result does not go as expected, in the example below the result should be 15, the result is only 3

   $mes1 = '2018-11-21';
   $mes2 = '2020-02-21';

   $data = new DateTime($mes1);
   $nova_data = $data->diff(new DateTime($mes2));
   $calculo = $nova_data->format('%m');

   $total_meses = $calculo;

   echo $total_meses;
  

From 2018-11-21 to 2020-02-21, the months difference is 15, but the php   says it's 3

result : 3

    
asked by anonymous 14.10.2018 / 01:23

2 answers

0
<?php

$mes1 = '2018-11-21';
$mes2 = '2020-02-21';

echo (int)abs((strtotime($mes1) - strtotime($mes2))/(60*60*24*30));
    
14.10.2018 / 02:42
0

I have decided this way:

$mes1 = new DateTime('2018-11-21');
$mes2 = new DateTime('2020-02-21');
$diff = $mes1 -> diff($mes2);
echo (($diff->format('%y') * 12) + $diff->format('%m')) . " Meses";
    
14.10.2018 / 03:55