What's happening on your site right now?

Find out with GoSquared. Real-time web analytics.


Try GoSquared Free.

Handy PHP function: Time breakdown

Geoff Wagstaff / May 23, 2010

Develop with Geoff at GoSquared

Due to the nature of the web apps we build, we’re constantly working with time-related logic, and have built up a small collection of functions to help ease the pain with these calculations. This particular function is useful for breaking down a unit of time, represented in seconds, into its constituent days:hours:minutes:seconds, the former two of which are omitted if not applicable.

/**
 * Converts seconds into days:hours:minutes:seconds components
 *
 * @param int $time - number of seconds
 * @return string
 */
 
function time_quanta($time){
	$d = intval(($time / 86400));
	$h = intval(($time / 3600) % 24);
	$m = intval(($time / 60) % 60);
	$s = intval($time % 60);
 
	if(!max($d,$h,$m,$s)) return false;
	$st = '';
	if($d>0) $st .= ($d < 10?'0'.$d:$d).':';
	if($h>0) $st .= ($h < 10?'0'.$h:$h).':';
	$st .= ($m < 10?'0'.$m:$m).':';
	$st .= ($s < 10?'0'.$s:$s);
 
	return $st;
}

The function can be particularly handy when you’d like to present debugging timers, which are usually counted in seconds or milliseconds (using time() or microtime() etc), in a more humanly readable format, especially if the times involved are long.

Who is on my website right now? Find out with GoSquared - real-time web analytics and traffic monitoring.

3 Responses so far Follow Comments on this Post with RSS

  1. 1

    Aaron Parker said,

    May 23, 2010 at 18:19 ()

    Just wondering if the code is meant to have the < parts in this section:
    $st .= ($m<10?'0'.$m:$m).':';
    $st .= ($s<10?'0'.$s:$s);
    Is this supposed to be a < sign? Could just be a funny formatting thing or I could just not know enough about PHP yet :P

    Thanks for sharing though as this looks like it could have many excellent uses!

    Aaron

  2. 2

    Aaron Parker said,

    May 23, 2010 at 18:21 ()

    That didn't quite go to plan as the formatting issue I was referring to was picked up by your comment form (how ironic :P). I was referring to the & lt; in the code (remove the space after the &).

    Aaron

  3. 3

    Geoff said,

    May 23, 2010 at 18:27 ()

    @Aaron - good spot! Thanks for pointing that out, it was some weird formatting error on wordpress' part there. It converted the less than symbols to their html entities which aren't rendered back to their symbols in the syntax highlighting. Fixed now!

· TrackBack URI

Have Your SaySigned in as | Sign Out

GoSquared Features - respond now, not tomorrow. GoSquared on Facebook - Keep up to date with us on Facebook GoSquared on Twitter - follow us why don't you! About GoSquared