28 Mar

This function will find the difference between two given times. Does PHP already have a native function for that?

//The difference between 2 given time
function dateDifference(\$day_1,\$day_2) {
\$diff = strtotime(\$day_1) - strtotime(\$day_2);

\$sec   = \$diff % 60;
\$diff  = intval(\$diff / 60);
\$min   = \$diff % 60;
\$diff  = intval(\$diff / 60);
\$hours = \$diff % 24;
\$days  = intval(\$diff / 24);

return array(\$sec,\$min,\$hours,\$days);
}

If you just want the day difference…

\$diff = strtotime(\$day_1) - strtotime(\$day_2) + 1; //Find the number of seconds
\$day_difference = ceil(\$diff / (60*60*24)) ;  //Find how many days that is

This can be done using the DATEDIFF function in MySQL 5

[tags]php,code,date,difference,time[/tags]

3 thoughts on “Find Difference Between 2 Dates in PHP”

1. \$date1 = date(‘Y-m-d’);
\$date2 = “2007-02-26″;
\$days = (strtotime(\$date1) – strtotime(\$date2)) / (60 * 60
* 24);
echo ” No of \$days difference”;

2. @chinmay:

above solution is good easy..

3. Nice and easy…I really need this for my current project…Thanks!