Created
December 4, 2014 21:51
-
-
Save rattrap/e4f0239f2efb8301d6d0 to your computer and use it in GitHub Desktop.
Time ago in PHP
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 | |
function time_ago($time) { | |
$time = time() - $time; | |
if($time < 5) { | |
return 'Just now'; | |
} | |
$units = array( | |
365 * 24 * 60 * 60 => 'year', | |
30 * 24 * 60 * 60 => 'month', | |
24 * 60 * 60 => 'day', | |
60 * 60 => 'hour', | |
60 => 'minute', | |
1 => 'second' | |
); | |
$units_plural = array( | |
'year' => 'years', | |
'month' => 'months', | |
'day' => 'days', | |
'hour' => 'hours', | |
'minute' => 'minutes', | |
'second' => 'seconds' | |
); | |
foreach($units as $seconds => $unit) { | |
$decimal = $time / $seconds; | |
if($decimal >= 1) { | |
$rounded = round($decimal); | |
$plural = $rounded > 1; | |
return $rounded . ' ' . ($plural ? $units_plural[$unit] : $unit) . ' ago'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment