## Difference between two dates in php

Suppose i have two dates in any format and i need to find the difference between the two dates , then the solution to find the difference between the two dates in php is given below:

You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it’s rather easy to calculate different time periods.

This following code will show you how to calculate difference between two dates by using PHP

Feel free to share

```function datedifference(\$date1,\$date2){

\$diff = abs(strtotime(\$date2) - strtotime(\$date1));

\$years   = floor(\$diff / (365*60*60*24));
\$months  = floor((\$diff - \$years * 365*60*60*24) / (30*60*60*24));
\$days    = floor((\$diff - \$years * 365*60*60*24 - \$months*30*60*60*24)/ (60*60*24));

\$hours   = floor((\$diff - \$years * 365*60*60*24 - \$months*30*60*60*24 - \$days*60*60*24)/ (60*60));

\$minuts  = floor((\$diff - \$years * 365*60*60*24 - \$months*30*60*60*24 - \$days*60*60*24 - \$hours*60*60)/ 60);

\$seconds = floor((\$diff - \$years * 365*60*60*24 - \$months*30*60*60*24 - \$days*60*60*24 - \$hours*60*60 - \$minuts*60));

if(\$years>0){
echo \$years.'y-'.\$months.'m-'.\$days.'d-'.\$hours.'h-'.\$minuts.'m-'.\$seconds.'s';
}

if(\$months>0&&\$years==0){
echo \$months.'m-'.\$days.'d-'.\$hours.'h-'.\$minuts.'m-'.\$seconds.'s';
}
if(\$days>0&&\$years==0){
echo \$days.'d-'.\$hours.'h-'.\$minuts.'m-'.\$seconds.'s';
}
if(\$hours>0&&\$months==0&&\$years==0){
echo \$hours.'h-'.\$minuts.'m-'.\$seconds.'s';
}
if(\$minuts>0&&\$hours==0&&\$months==0&&\$years==0){
echo \$minuts.'m-'.\$seconds.'s';
}
if(\$seconds>0&&\$minuts==0&&\$hours==0&&\$months==0&&\$years==0){
echo \$seconds.'s';
}
}```  