Hello! I have 2 dates.

$ d1 = "2017-09-01"; $ d2 = "2017-09-30";

I think the difference between dates is as follows:

echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); 

The question is how to correctly calculate the difference between dates, including all the nuances of the number of days in a month, since I would like to get a result in this particular case 1 - Ie 1 month, since from 1 to 30 September inclusively there is 1 month, but in fact I see 0 as if the month is not full, but if we count from 2017-09-01 to 2017-10-01, it will already be 1

  • If DateTime :: diff is offered in the answer, do not flatter yourself, he also lies :) ru.stackoverflow.com/a/640839/186083 PS This is not a link to mark duplicate !!! - Visman
  • why lies at once? From 1 to 30 and the truth will be 0 and not 1 month, since the day will not be over, dive 1 day to the date and count. - Bookin
  • @Bookin, 2016-11-30 - 2017-03-01 выдаёт 2 of the question on my link. Must 3 issue;) And from 1 to 30 is really not a full month, I agree with you. - Visman

1 answer 1

There is a date_diff function for this.

 $d1 = date_create('2017-09-01'); $d2 = date_create('2017-09-30'); $interval = date_diff($d1, $d2); echo $interval->format('%m'); 

Here is the solution through the "crutch"

 function dt_diff($d1,$d2){ $d1 = date_create($d1); $d2 = date_create($d2); if ($d1>$d2) {$td=$d1;$d1=$d2;$d2=$td;} $yr= date_format ($d2,'Y') - date_format ($d1,'Y'); $mr = date_format ($d2,'m') - date_format ($d1,'m'); $dr= date_format ($d2,'d') - date_format ($d1,'d'); $dr = ($dr<0) ?-1 :0; $r= $yr*12 +$mr+$dr; return $r;} 

And checking http://sandbox.onlinephpfunctions.com/code/f70037cfbf0178f07640552ce5b6e4a114c04252