Without using PHP 5.3\'s date_diff function (I\'m using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don
Follow up on the answer of @deceze (I've upvoted on his answer). Month will still count as a whole even if the day of the first date didn't reached the day of the second date.
Here's my simple solution on including the day:
$ts1=strtotime($date1);
$ts2=strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
$day1 = date('d', $ts1); /* I'VE ADDED THE DAY VARIABLE OF DATE1 AND DATE2 */
$day2 = date('d', $ts2);
$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
/* IF THE DAY2 IS LESS THAN DAY1, IT WILL LESSEN THE $diff VALUE BY ONE */
if($day2<$day1){ $diff=$diff-1; }
The logic is, if the day of the second date is less than the day of the first date, it will reduce the value of $diff
variable by one.