PHP: Date difference in days

You might need to calculate the date difference in days using PHP. You can easily calculate the days difference by using something like the code below.

function datediff($date1, $date2) {
  return round(abs(strtotime($d1) - strtotime($d2)) / (60 * 60 * 24));

The code shown above takes the UNIX timestamp of two dates and subtracts the one date from the other to get the number of seconds. Then we simply divide the seconds by 60 (since there are 60 seconds in a minute) to get the minutes, again by 60 (since there are 60 minutes in an hour) to get the hours and lastly by 24 (since there are 24 hours in a day) to get the number of days.

You don’t have to subtract the newer date from the older date though since we’re making use of the php abs() function which will automatically return an absolute value and eliminate a minus sign to make a negative value positive.

I hope that helps!

%d bloggers like this: