Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created January 9, 2018 12:25
Show Gist options
  • Save mscalora/c069724115e1042d449435301ee3957c to your computer and use it in GitHub Desktop.
Save mscalora/c069724115e1042d449435301ee3957c to your computer and use it in GitHub Desktop.
Return a duration (in seconds) in a humanized string format like: "2 seconds" or "1 year"
function humanizeDuration ($secs) {
$secs = ($secs<1)? 1 : $secs;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($secs < $unit) continue;
$numberOfUnits = floor($secs / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment