Skip to content

Instantly share code, notes, and snippets.

@youssman
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youssman/0b858cf3c3ea38397e22 to your computer and use it in GitHub Desktop.
Save youssman/0b858cf3c3ea38397e22 to your computer and use it in GitHub Desktop.
<?php
// DISPLAYS COMMENT POST TIME AS "1 year, 1 week ago" or "5 minutes, 7 seconds ago", etc...
function time_ago($date,$granularity=2) {
$date = strtotime($date);
$difference = time() - $date;
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
if ($difference < 5) { // less than 5 seconds ago, let's say "just now"
$retval = "posted 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 ' posted '.$retval.' ago';
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment