Many popular social networking sites such as Digg or Twitter don’t display dates like Published on June 25. Instead, they display Published 10 days ago.
Here’s a PHP function to convert a date into a “time ago” date.
function timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
$difference = time() - $timestamp;
if($difference < 0) return '0 seconds ago';
elseif($difference < 864000){
$periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
$output = '';
foreach($periods as $key => $value){
if($difference >= $value){
$time = round($difference / $value);
$difference %= $value;
$output .= ($output ? ' ' : '').$time.' ';
$output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
$granularity--;
}
if($granularity == 0) break;
}
return ($output ? $output : '0 seconds').' ago';
}
else return date($format, $timestamp);
}
Usage
$time = timeAgo($dateRef);
The function takes 3 parameters:
- timestamp: Your date
- granularity: How far you go in the precision of your date. Default is 2 (1 day, 15 hours ago)
- format: Desired format for the date. Default is Y-m-d H:i:s.
Using the timeAgo() function within WordPress
Using timeAgo() in WordPress is not hard at all. Use the following code within WordPress loop to display the “time ago” date of a post:
echo timeAgo(get_the_time('U'));

3 Comments
Nice snippet, thanks!
WordPress already has the
human_time_diff()function.[?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?]More in the Codex
http://codex.wordpress.org/Function_Reference/human_time_diff
Thanks for the tips, it’s better like this!
5 Trackbacks
[...] This post was mentioned on Twitter by Jean-Baptiste Jung and Pierpaolo Frigerio, PHP Snippets. PHP Snippets said: PHP Snippet: Display dates as “time ago” http://bit.ly/bX9ddY #php [...]
[...] PHP Snippets. If you enjoyed this article, please consider sharing it! tweetmeme_style = 'compact'; [...]
[...] Credits: PHP Snippets. [...]
[...] Snippets has a copy-and-paste-able function that works in much the same way. It takes a UNIX timestamp as an input and uses the [...]
[...] Credits: PHP Snippets. [...]