Last active
January 15, 2020 14:09
-
-
Save squallstar/1816183 to your computer and use it in GitHub Desktop.
Posted x time ago (PHP function)
This file contains hidden or 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($date,$granularity=2) { | |
$difference = time() - $date; | |
$retval = ''; | |
$periods = array('decade' => 315360000, | |
'year' => 31536000, | |
'month' => 2628000, | |
'week' => 604800, | |
'day' => 86400, | |
'hour' => 3600, | |
'minute' => 60, | |
'second' => 1); | |
if ($difference < 60) { // less than 60 seconds ago, let's say "just now" | |
$retval = "added just now"; | |
return $retval; | |
} else { | |
foreach ($periods as $key => $value) { | |
if ($difference >= $value) { | |
$time = floor($difference/$value); | |
$difference %= $value; | |
$retval .= ($retval ? ' ' : '').$time.' '; | |
$retval .= (($time > 1) ? $key.'s' : $key); | |
$granularity--; | |
} | |
if ($granularity == '0') { break; } | |
} | |
return ' added '.$retval.' ago'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment