Skip to content

Instantly share code, notes, and snippets.

@efarem
Last active December 21, 2015 01:59
Show Gist options
  • Save efarem/6231502 to your computer and use it in GitHub Desktop.
Save efarem/6231502 to your computer and use it in GitHub Desktop.
Convert a timestamp into a relative string e.g. 2 Hours ago
<?php
/**
* Convert a timestamp into a relative string e.g. 2 Hours ago
*
* @return string
*
* @param $time Timestamp
**/
function time_elapsed($time)
{
$etime = time() - $time;
if ($etime < 1)
{
return '0 seconds';
}
$a = array(
12 * 30 * 24 * 60 * 60 => 'Year',
30 * 24 * 60 * 60 => 'Month',
24 * 60 * 60 => 'Day',
60 * 60 => 'Hour',
60 => 'Minute',
1 => 'Second',
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . $str . (($r > 1) ? 's ago' : ' ago');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment