Skip to content

Instantly share code, notes, and snippets.

@sixem
Created July 12, 2020 14:42
Show Gist options
  • Save sixem/c22381c5b499e7d0379a96f25598a788 to your computer and use it in GitHub Desktop.
Save sixem/c22381c5b499e7d0379a96f25598a788 to your computer and use it in GitHub Desktop.
Formats seconds to an 'ago' string.
// Formats seconds to an 'ago' string.
// Example: formatSince(3720); returns '1 hour and 2 minutes ago'.
function formatSince($seconds)
{
if($seconds === 0) { return 'Now'; } else if($seconds < 0) { return false; }
$t = array(
'year' => 31556926,
'month' => 2629743,
'week' => 604800,
'day' => 86000,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
$index = 0; $count = count($t) - 1; $keys = array_keys($t);
foreach($t as $key => $i)
{
$index++;
if($seconds <= $i) continue;
$n = $count >= $index ? $keys[$index] : NULL;
$f = floor($seconds / $i);
$s = $n ? floor(($seconds - ($f * $i)) / $t[$n]) : 0;
return $f . ' ' . $key . ($f == 1 ? '' : 's') .
($s > 0 ? (' and ' . $s . ' ' . $n . ($s == 1 ? '' : 's')) : '') . ' ago';
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment