PHP Snippet – Time difference between 2 date/time stamps.
In a recent project I needed to capture how long the user spent on the application, it was not expected they would spend days on it so it return hours minutes seconds which can be saved to a database.
So basically here is a function to do that…
//
echo getTimeDifference("2010-02-26 18:35:36");
function getTimeDifference($start_time){
//convert $start_time into a usable string
$tempStart = preg_replace('/(\d{2})-(\d{2})-(\d{2})(.*)/', '$1:$2:$3:$4',$start_time);
$tempStart=explode(":",$tempStart);
$year = $tempStart[0];
$month= $tempStart[1];
$day = $tempStart[2];
$hour = $tempStart[3];
$minute = $tempStart[4];
$second = $tempStart[5];
//set the end time as current time
$timesEnd = date("Y:m:d:H:i:s");
$tempEnd=explode(":",$timesEnd);
$year1 = $tempEnd[0];
$month1= $tempEnd[1];
$day1 = $tempEnd[2];
$hour1 = $tempEnd[3];
$minute1 = $tempEnd[4];
$second1 = $tempEnd[5];
$countdown_date = mktime($hour, $minute, $second, $month, $day, $year);
$countdown_date1 = mktime($hour1, $minute1, $second1, $month1, $day1, $year1);
$diff = $countdown_date1 -$countdown_date ;
if ($diff < 0)
$diff = 0;
$dl = floor($diff/60/60/24);
$hl = floor(($diff - $dl*60*60*24)/60/60);
$ml = floor(($diff - $dl*60*60*24 - $hl*60*60)/60);
$sl = floor(($diff - $dl*60*60*24 - $hl*60*60 - $ml*60)
);
$timeDifference = "$hl:$ml:$sl";
return $timeDifference;
}
| Comment (RSS) | Trackback
Leon Wilson spends most of his time designing and developing flash sites, and wishes he was better at high end 3D.