X

How To Convert a Date / Timestamp to “Time Ago” Timestamp for Posts

Snippets by IsItWP

Are you looking for a way to convert a date/timestamp to “time ago” timestamp for posts? Displaying an exact date on your posts is great, but why not change things up just a little and display “1 Hour Ago”, “2 Hours Ago”, “1 Day Ago”, “2 Days Ago”, “1 Week Ago”, etc. This snippet lets you create a “time ago” timestamp like social media websites use.

Instructions:

Add this code to your theme’s functions.php file or in a site-specific plugin:

function time_ago( $type = 'post' ) {
    $d = 'comment' == $type ? 'get_comment_time' : 'get_post_time';
    return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago');
}

Then just add this snippet to your single.php file, index.php file, or any other template within The Loop. For example, you can replace the the_time() function with time_ago().

<?php
        echo time_ago();
?>

For a more advanced version, this snippet will create a timestamp that will change to the date after a certain time. Then just add this snippet to your single.php file, index.php file, or any other template within The Loop. Edit line 9 to use the number of seconds you want before the timestamp will change to the date.

<?php 
# For posts & pages #
echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
# For comments #
echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; 

// Change to the date after a certain time
$time_difference = current_time('timestamp') - get_the_time('U');
if($time_difference < 86400) {
	//here goes the code from one of the sample above
} else {
	the_time();
};
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 6 best Stripe payment plugins for WordPress and how to create a review site in WordPress.

Comments   Leave a Reply

  1. maybe you should start thinking about internationalising your snippets, we’re living in the 21st century after all…

    1. Lots of things I would like to add to the site, however only so much time in a day. This is a good idea though, thanks.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!