4
I need to count the amount 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 well when the dates are well separated, but my problem occurs when I want to compare two dates like.
$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), in the same way if I use.
$data1 = '2017-06-20';
$data2 = '2017-08-01';
need to be accounted for 2 months.
Does anyone have any suggestions?.
So it doesn’t matter what day? You just want to know the number of months that went into play?
– Sam
In the case of
$data1 = '2017-08-01';
and$data2 = '2017-09-01';
, what should return?– Sam
Should return 1 in case of passage of the month 08 to the month 09.
– Marcos Paulo
Even ignoring the 30 days passed between dates?
– Sam
That’s right, amount of days is not interesting, I just need to know how many months "turned" according to the beginning and end
– Marcos Paulo