Last active
December 21, 2015 01:59
-
-
Save efarem/6231502 to your computer and use it in GitHub Desktop.
Convert a timestamp into a relative string e.g. 2 Hours ago
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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