I need to count the number of months that turned from two dates using PHP
, I have the following code to calculate the difference of months between 2 dates.
$data1 = '2017-01-01';
$data2 = '2017-03-01';
$date = new DateTime($data1);
$diferenca = $date->diff(new DateTime($data2));
$diferenca_anos = $diferenca->format('%Y')*12;
$diferenca_meses = $diferenca->format('%m');
$total_meses = $diferenca_anos+$diferenca_meses;
echo $total_meses;
The code works fine when the dates are well separated, however my problem occurs when I want to compare two dates as.
$data1 = '2017-06-20';
$data2 = '2017-07-01';
In the above case my code returns 0, months, but I need it to count as if it had "turned" a month (from June to July), the same way I use it.
$data1 = '2017-06-20';
$data2 = '2017-08-01';
need to be accounted for 2 months.
Does anyone have any suggestions?