Sep 19, 2008

PHP: calculating time span duration

I needed a function to print a preety time span duration. Nothing special, just simple as that. It turned out to be usefull for many things, like machine (or any other) uptime and so on. Return value is something simmilar to
6 days 3 hours 34 minutes 13 seconds
So here goes, the duration() function. It's published here, so I don't have to waste time and reinvent this everytime.
/*
  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;
}

3 comments:

Anonymous said...

very good

Andrew said...

Nice, But!
This doesn't work for me without modification.
The PHP manual states "The default value [for a function argument] must be a constant expression, not (for example) a variable, a class member or a function call."

So it seems that $end=time() is not allowed in the declaration. Did this ever work for you?

Try altering the begging of the code as such:

function duration($start,$end=null) {
if ( $end == null) { $end = time(); }

jeancaffou said...

Hey, nice catch.

I think it worked fine in PHP 4. But then I changed the function, before migrating to PHP 5.

I'll fix the code. Thanks.