PHP : Date difference in days

Tue, Jun 17, 2008

PHP

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.

<?php

//date in the past.
$date1 = "2008-04-11";
//current date.
$date2 = date("Y-m-d", time());
//calculate the difference in seconds.
$difference = abs(strtotime($date2) - strtotime($date1));
//calculate the number of days
$days = round(((($difference/60)/60)/24), 0);

?>

The code shown above takes the UNIX timestamp of two dates and subtracts the older date from the newer date 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!

, , , ,
scriptlancebannerpng

This post was written by:

Antonie Potgieter - who has written 46 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

3 Comments For This Post

  1. Kavita Says:

    Really helpful!!!!!!!!!

  2. Iain Says:

    Indeed.

    I was working on an old site that only had version 4.0 of MySQL installed so no DATEDIFF command.

    Your code above allowed me to do the calculation almost as easily in PHP.

  3. lolyz Says:

    ohh dear..itz so easy…just tell me how to get end date from starting date and number of days + time , and also eliminate the weekends..

Leave a Reply