Twitter Style Time: “Posted n Seconds/Minutes/Hours/Days Ago” (and WordPress Shortcode to Reference Other Posts)

The Twitter and Facebook style of referencing time since a post was published is becoming increasingly popular. Basically, instead of a standard date and time, both platforms will display a post timestamp in simple language (example: Posted 5 hours ago, Posted 2 days ago, Posted 15 seconds ago… and so on). This timestamp functionality is being evaluated for inclusion in the redesign of one of our websites.

The ‘problem’ with standard dates – if you can call it that – is that you need to know the current date or time for reference (granted, it’s not a big problem). Displaying the post time in a readable string is simply a more elegant solution.

This post will detail how to:

  • Use WordPress Shortcode to render date/time into a readable string.
  • Use WordPress shortcode to display the date of the next scheduled post.
  • Use PHP code to convert date/time into a real-time readable string.

In playing around with this code I came up with a large number of possible applications. Rather than trying to include them all, you can obviously alter the code to do whatever it is you want it to.

Time Text in WordPress Posts and Pages

Some time back, I provided code that would ‘dynamically’ count down days until an event. The following is far more functional and easier to use (although the previous function counts down exact days… sometimes preferable). The time/date combination that you’ll use in your shortcode is based on PHP’s strtotime() (String to Time) function.

The strtotime() function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp. Example formats can be found here or here.

You can play around with various UNIX Timestamp formats here.

The most commonly acceptable format (that you should use in your shortcode) is as follows: 2012-07-16 11:50… although something more advanced like this is far more powerful: Mon July 30 18:00:00 +1000 2012. The +1000 indicates that the event is Greenwich Time + 10 hours (for Sydney). Advanced usage makes it exceedingly easy to count down (or up) to events in different time zones.

Shortcode Usage:

Used in your WordPress post, the shortcode of [mytime date="Mon July 30 18:00:00 +1000 2012"] would render the following text: 11 months ago. To count down the days until the 2016 Rio De Janeiro Olympics (in 2016), I would use [mytime date="Thursday August 05 18:00:00 -0300 2016"] (August, 5th 2016, at 6pm local time [GMT minus 3hrs]). This shortcode will render as 3 years from now.

If we used the function that I provided 3 years ago (yes, I displayed that time reference using shortcode) to count down the days to the Rio Olympics, it would display as: 1142 more days until Rio Olympics. The Rio Olympics website provides a similar countdown on its home page.

Display Details of the Next Scheduled Post

We’ve looked at how to display future scheduled posts in a previous post. This shortcode is a variation on the same theme.

The shortcode of [mytime date="next"] will render the following into a WordPress post or page: The next post, entitled Post to a Facebook Page with PHP, is scheduled 5 months from now. You could easily style the next post and, say, have it displayed prominently under each post. My example follows:


The next post, entitled Post to a Facebook Page with PHP, is scheduled 5 months from now


Shortcode Function

You’ll want to copy the following code into your theme’s functions.php file, or, if you have it, your custom functions file. Alternatively, a plugin is included in the download package below.

function stringTime($atts) {
    extract(shortcode_atts(array(
	'date' => '',
	'id' => ''
    ), $atts));

  global $wpdb;
  $oDate = $date;

  if ($date == "next") {
      $posts = $wpdb->get_results("SELECT post_title, post_date FROM $wpdb->posts WHERE (post_type = 'post') AND (post_status = 'future') ORDER BY post_date LIMIT 1");
      $numberResults = $wpdb->num_rows;

        if ($numberResults == "0") {
        $return = "<strong>No future posts scheduled.</strong>";
        } else {
	 foreach ($posts as $post) {
	 setup_postdata($post);
         $date = $post->post_date;
         $title = $post->post_title;
	 }
        }
    }

    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");

    $now = current_time('timestamp');
    $unix_date = strtotime($date);

    // Determine tense of date
    if($now > $unix_date) {
    $difference = $now - $unix_date;
    $tense = "ago"; } else {
    $difference = $unix_date - $now;
    $tense = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
    $difference /= $lengths[$j];
    }
 
    $difference = round($difference);

    if($difference != 1) {
    $periods[$j].= "s";
    }

  if (($oDate == "next") && ($numberResults != "0")) {
  return "The next post, entitled <em><strong>$title</strong></em>, is scheduled $difference $periods[$j] {$tense}";
  }
  if ($oDate != "next") {
  return "$difference $periods[$j] {$tense}";
  }
  if ( ($oDate == "next") && ($numberResults == "0") ){
  return "No future posts scheduled... yet.";
  }
}
add_shortcode("mytime", "stringTime");

The WordPress plugin (included in the download package below) will activate the same way as any other plugin.

PHP Function

This is the standard PHP function to be used outside of WordPress.

Usage:

$date = “2012-07-16 11:50″;
$result = time_difference($date);
echo $result;

<?php
// Time Difference
function time_difference($date)
{
 if(empty($date)) {
 return "No date provided"; 
 }
 
 $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
 $lengths = array("60","60","24","7","4.35","12","10");

 $now = time();
 $unix_date = strtotime($date);

 // Check validity of date
 if(empty($unix_date)) {
 return "Bad date"; 
 }

 // Determine tense of date
 if($now > $unix_date) {
 $difference = $now - $unix_date;
 $tense = "ago"; } else {
 $difference = $unix_date - $now;
 $tense = "from now";
 }

 for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
 $difference /= $lengths[$j];
 }
 
 $difference = round($difference);

 if($difference != 1) {
   $periods[$j].= "s";
   }

  return "$difference $periods[$j] {$tense}";
}

// Acceptable Dates
// See http://php.net/manual/en/function.strtotime.php
// GMT reference:
// Thursday August 05 18:00:00 -0300 2016

$date = "2012-07-16 11:50";
$result = time_difference($date);
echo $result;
?>

If you have any issues, please let me know.

First Name:
Your Email Address:
 




Download: Twitter Style Countdown Shortcode
Description: Twitter Style Countdown Shortcode (and WP Plugin).
Author:Marty
Category: PHP code
Date: July 30, 2012



If you liked this article, you may also like:

  1. Display Future (Scheduled) WordPress Posts with Shortcode
  2. Generate Random WordPress Posts with Shortcode
  3. Automate WordPress Posts to Twitter (with hastags, truncation and a short URL)
  4. YouTube Thumbnails in WordPress Posts with Shortcode
  5. Add a WordPress Featured Image Preview to Your Posts Menu

Comments

  1. Michael says:

    Can you change the time format in WordPress posts also?

  2. Marty says:

    Hi Michael. I assume you mean in the byline of your post? If so, sure.

    For posts & pages:

    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';

    It uses WP’s human_time_diff function. There are various hooks and filters that you could play with but I’m yet to have a go myself.

Speak Your Mind

*