Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created June 20, 2012 16:02
Show Gist options
  • Save mlconnor/2960665 to your computer and use it in GitHub Desktop.
Save mlconnor/2960665 to your computer and use it in GitHub Desktop.
Creates a nice duration given a number of seconds. For example, 1h 28m
function nice_duration($seconds, $maxFragments = 0) {
// Define time periods
$periods = array (
'y' => 31556926,
'mo' => 2629743,
'wks' => 604800,
'd' => 86400,
'h' => 3600,
'm' => 60,
's' => 1
);
$fragments = array();
$seconds = (float) $seconds;
foreach ($periods as $period => $pSec) {
$pCount = (int) floor($seconds / (float) $pSec);
if ( $pCount >= 1 ) {
$seconds -= $pCount * $pSec;
$fragments[]= $pCount . $period;
}
if ( $maxFragments > 0 && count($fragments) >= $maxFragments ) {
break;
}
}
return count($fragments) > 0 ? implode(' ', $fragments) : "1s";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment