Twitter like N min/sec ago timestamp in PHP/MySQL

While working on one of the forum project, I had to print the timestamp of a topic in format “N Seconds ago” or “X minutes ago”.! The Web 2.0 world have changed the way these dates are displayed. The days are gone when the timestamps were displayed like “12 Jan 2003 10:50 pm”!!! A paradigm shift have changed the world to more “Live” stream based systems. Now the Web pages are not just data wrapped in HTML, but they have became more real with realtime interaction between people. And thus the timestamps also got changed to “2 mins ago”, “5 hours ago” like formats. This identify more lively the streams and you can visualize them as events happened just minutes ago.

Enough Gyan, let’s see the code…

Following is the PHP function that can be used to convert the timestamp into Twitter like “X min ago” format.

/* Works out the time since the entry post, takes a an argument in unix time (seconds) */ static public function Timesince($original) { // array of time period chunks $chunks = array( array(60 * 60 * 24 * 365, 'year'), array(60 * 60 * 24 * 30, 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24, 'day'), array(60 * 60, 'hour'), array(60, 'min'), array(1, 'sec'), ); $today = time(); /* Current unix time */ $since = $today - $original; // $j saves performing the count function each time around the loop for ($i = 0, $j = count($chunks); $i < $j; $i++) { $seconds = $chunks[$i][0]; $name = $chunks[$i][1]; // finding the biggest chunk (if the chunk fits, break) if (($count = floor($since / $seconds)) != 0) { break; } } $print = ($count == 1) ? '1 ' . $name : "$count {$name}s"; if ($i + 1 < $j) { // now getting the second item $seconds2 = $chunks[$i + 1][0]; $name2 = $chunks[$i + 1][1]; // add second item if its greater than 0 if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { $print .= ($count2 == 1) ? ', 1 ' . $name2 : " $count2 {$name2}s"; } } return $print; } [/code] <!-- /wp:shortcode --> <!-- wp:paragraph --> <p>Input to this function will be timestamp in Unix seconds. If your database table has timestamp field than you can convert it into Unix timestamp by using UNIX_TIMESTAMP () method in MySQL. </p> <!-- /wp:paragraph --> <!-- wp:shortcode --> <!-- wp:code {"language": "sql"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> SELECT id, username, UNIX_TIMESTAMP(joined_data) from UserTable;
Code language: PHP (php)

Update: Download PHP Smarty template custom function to generate twitter like timestamps.

If you think this little code snippet might be useful in future then feel free to bookmark it and share it.

View Comments

  • When unix time is under a minute, it shows 0 mins as opposed to x seconds.

    Is this how it is meant to perform? If so, how could you add seconds to it?

  • I guess it was as easy as adding:

    $chunks = array(
     array(60 * 60 * 24 * 365 , 'year'),
     array(60 * 60 * 24 * 30 , 'month'),
     array(60 * 60 * 24 * 7, 'week'),
     array(60 * 60 * 24 , 'day'),
     array(60 * 60 , 'hour'),
     array(60 , 'min'),
     array(1, 'sec'),
    );
    
  • Thanks Nathan for adding "seconds" to the code. I have added your changes to main code.

  • You can always convert a date to unix timestamp in PHP and leave the mysql part out of your example ;-)
    Just use strtotime()

  • Hemm I cant seem to get this to work I have a add_post function that add's the users post and as well as the time stamp. and I am trying to do this

    $sql = "insert into posts (user_id, body, stamp)
    values ($userid, '" . mysql_real_escape_string($body) . "', '". $print ."')";

    This ^^^^ is from another function

  • <?php

    function Timesince($original) {
    // array of time period chunks
    $chunks = array(
    array(60 * 60 * 24 * 365 , \'year\'),
    array(60 * 60 * 24 * 30 , \'month\'),
    array(60 * 60 * 24 * 7, \'week\'),
    array(60 * 60 * 24 , \'day\'),
    array(60 * 60 , \'hour\'),
    array(60 , \'min\'),
    array(1 , \'sec\'),
    );

    $today = time(); /* Current unix time */
    $since = $today - $original;

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

    $seconds = $chunks[$i][0];
    $name = $chunks[$i][1];

    // finding the biggest chunk (if the chunk fits, break)
    if (($count = floor($since / $seconds)) != 0) {
    break;
    }
    }

    $print = ($count == 1) ? \'1 \'.$name : \"$count {$name}s\";

    if ($i + 1 < $j) {
    // now getting the second item
    $seconds2 = $chunks[$i + 1][0];
    $name2 = $chunks[$i + 1][1];

    // add second item if its greater than 0
    if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
    $print .= ($count2 == 1) ? \', 1 \'.$name2 : \" $count2 {$name2}s\";
    }
    }
    return $print;
    }
    /*
    $body = str_replace(\":)\",\"<img src=\\\"img/smilehappy.png\\\">\",$body);
    $body = str_replace(\":(\",\"<img src=\\\"img/smilesad.png\\\">\",$body);
    $body = str_replace(\"X(\",\"<img src=\\\"img/smilemad.png\\\">\",$body);
    $body = str_replace(\"o.O\",\"<img src=\\\"img/smileoO.png\\\">\",$body);
    $body = str_replace(\"><\",\"<img src=\\\"img/smilesquint.png\\\">\",$body);
    $body = str_replace(\">_<\",\"<img src=\\\"img/smileninja.png\\\">\",$body);
    $body = str_replace(\":S\",\"<img src=\\\"img/smilesick.png\\\">\",$body);
    $body = str_replace(\"zZz\",\"<img src=\\\"img/smileZz.png\\\">\",$body);
    $body = str_replace(\"oO\",\"<img src=\\\"img/smilepo.png\\\">\",$body);
    */

    $Psql=\"SELECT F.`follower_id`, FU.username AS Name, U.`username` AS followerName
    FROM `following` F
    JOIN users U ON U.`id` = F.`user_id`
    JOIN users FU ON FU.`id` = F.`follower_id`
    WHERE F.`user_id` =\". $_SESSION[\'userid\'] .\"
    LIMIT 0 , 3\";

    $Presult = mysql_query($Psql);
    while($Prows = mysql_fetch_array($Presult)){
    $Ppsql=\"SELECT `body`, UNIX_TIMESTAMP(stamp) FROM `posts` WHERE `user_id` = \'\". $Prows[\'follower_id\'] .\"\' ORDER BY `stamp` DESC LIMIT 0,3\";
    $Ppresult=mysql_query($Ppsql);
    while($Pprows = mysql_fetch_array($Ppresult)){
    echo \"<strong><a href=\\\"/\". $Prows[\'Name\'] .\"\\\"><font color=black>\".$Prows[\'Name\'] .\"</font></a></strong> | \". $Pprows[\'body\'] .\" | \". $Pprows[\'stamp\'] .\"<hr><br>\";
    }
    }

    ?>

  • Used this and it worked straight out the box. Good work, thanks for sharing.

Share
Published by
Viral Patel
Tags: live stream MySQL PHP php code snippet web 3.0

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago