Skip to content

Instantly share code, notes, and snippets.

@squallstar
Last active January 15, 2020 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squallstar/1816183 to your computer and use it in GitHub Desktop.
Save squallstar/1816183 to your computer and use it in GitHub Desktop.
Posted x time ago (PHP function)
<?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