How to Display Count Published Day and Time Ago

Getting the right kind of time

You’d think that if you want to count how many days ago a post was posted you could just grab the dates and count backwards. But that’s actually pretty hard because it relies on the counting mechanism knowing what day of the month it is and how many days each month has etc etc. A better solution is to grab a unified time value that doesn’t change in the same arbitrary way. Luckily programmers found this problem and its solution a long long time ago. It is called the the Unix Epoch and is the time, in seconds, since January 1, 1970 00:00:00 GMT). To get this value for each of our functions we simply add in the format string “U” like this:

date('U'); // outputs the current date and time in Unix Epoch terms
get_the_time('U'); // outputs the publishing date and time in Unix Epoch terms

Making the time make sense

Problem is this produces a weird long number like 6250458. This is the number of seconds since the article was published. We want the number of days, so we need to do some math.

If you have seconds and you want to make days you first have to divide them by 60 to make minutes, then divide it by 60 again to make hours and then finally divide it by 24 to make days. For 86399 out of every 86400 seconds of the day this will produce an integer (number with a comma) but we want whole numbers. So we utilize an extra function called round() that rounds out the number for us.

Putting it together

It is easy for you to display days ago in your website, just copy code bellow and then past into your templates.

Sample 1

Easy ways you can use the function in your theme files
<?php
	$days = round((date('U') - get_the_time('U')) / (60*60*24));
	echo "Published " . $days . " days ago";
?>

Sameple 2

Easy ways you can use the function in your theme files
<?php
	$days = round((date('U') - get_the_time('U')) / (60*60*24));
	if ($days==0) {
		echo "Published today";
	}
	elseif ($days==1) {
		echo "Published yesterday";
	}
	else {
		echo "Published" . $days . " days ago";
	}
?>

Sample 3

Easy ways you can use the function in your theme files

Posted <?php echo human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’; ?>

 

Sample 4  Display Time ago

Step1 you need to copy code bellow and paste it into the functions.php file and you are ready to go. No more messing needed.

add_filter('the_time', 'timeago');

function timeago()
{
    global $post;

    $date = $post->post_date;

    $time = get_post_time('G', true, $post);

    $time_diff = time() - $time;

    if ( $time_diff > 0 && $time_diff < 24*60*60 )
        $display = sprintf( __('%s ago'), human_time_diff( $time ) );
    else
        $display = date(get_option('date_format'), strtotime($date) );

    return $display;
}

Step2 Once done, you can use the function in your theme files:

<?php echo timeago(); ?>