Count difference of months between dates

Asked

Viewed 48 times

0

I took this example right here, it works, however it does not work the way I expected, I need to take the amount of months between dates, but the result does not come out as expected, in the example below the result should be 15, however 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 difference of months is 15, but php says it’s 3

outworking: 3

  • 1 year and 3 months. If you give a echo $nova_data->format('%y'); will see that the return is 1

  • Do you know how I can get this account? I would need a direct return, like: 15

  • 2

    $calculo = $nova_data->m + ($nova_data->y * 12);

  • 1

    https://answall.com/a/134313/60376

  • It worked, thank you

2 answers

0

<?php

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

echo (int)abs((strtotime($mes1) - strtotime($mes2))/(60*60*24*30));

0

I resolved it 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";

Browser other questions tagged

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