How to calculate difference between two dates in PHP

Today I want to share with you my new php function to calculate difference between two dates. I have created the function to calculate the time when an user was online.

function get_time_difference($time1,$time2)
{
$date1=date_create($time1);
$date2=date_create($time2);
$diff=date_diff($date1,$date2);
if($diff->format("%a") > 0):
echo "Was online ".$diff->format("%a")." days ago";
elseif($diff->format("%i") > 0):
if($diff->format("%h") > 0):
echo "Was online ".$diff->format("%h")." hours ago";
else:
echo "Was online ".$diff->format("%i")." minutes ago";
endif;
else:
echo "is online";
endif;
}

get_time_difference("2010-01-01 05:08:20",date("Y-m-d H:i:s"));

In this ways I have solved my problem.









Leave a Comment