Handy PHP function: Time breakdown

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.

Subscribe to the GoSquared newsletter.

Join 15,000 people. Get our latest posts delivered to your inbox every week.