odenijs
7/31/2013 - 1:28 PM

Simple timespan calculation

Simple timespan calculation

/*
  Input parameter is the UNIX timestamp
  of the starting date.
  The second parameter is optional -
  It's value is the ending date,
  also UNIX timestamp. If this
  parameter is not given, the
  default date is current date.
*/
function duration($start,$end=null) {
$end = is_null($end) ? time() : $end;
 
$seconds = $end - $start;
 
$days = floor($seconds/60/60/24);
$hours = $seconds/60/60%24;
$mins = $seconds/60%60;
$secs = $seconds%60;
 
$duration='';
if($days>0) $duration .= "$days days ";
if($hours>0) $duration .= "$hours hours ";
if($mins>0) $duration .= "$mins minutes ";
if($secs>0) $duration .= "$secs seconds ";
 
$duration = trim($duration);
if($duration==null) $duration = '0 seconds';
 
return $duration;
}