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

x-min-sec-ago-timestamp

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.

Get our Articles via Email. Enter your email address.

You may also like...

16 Comments

  1. Nathan says:

    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?

  2. Nathan says:

    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'),
    );
    
  3. Thanks Nathan for adding “seconds” to the code. I have added your changes to main code.

  4. BTM says:

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

  5. f055 says:

    Isn’t it easier to just use datetime multiplication functions of MySQL and NOW() ?

  6. John says:

    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

  7. <?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>\";
    }
    }

    ?>

  8. babu says:

    ya its really nice

  9. bsides says:

    I used this today and works flawlessly. Thanks a lot :)

    • @bsides – Thanks for the comment. Feel free to use the code from this site.

  10. Michael Fitzmaurice says:

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

  11. Carlos K says:

    I’ve ported this to JS, if anyone is interested. This would allow the page up be updated with the current “time since” in real time: http://pastebin.com/e4chahvG

  12. Carlos K says:

    Updated to fix some small errors: http://pastebin.com/e4chahvG

  13. Aaron Cruz says:

    If you are using this for your own Twitter feed reader, just send a strtotime($created_at_string_from_twitter_timeline) into the function as the parameter.
    And thanks. This is way prettier than my version. I will definitely put a link to this post in my new stolen version!

  14. Thanks a lot! very useful

  15. annie says:

    For what purpose this code is i m not getting..

Leave a Reply

Your email address will not be published. Required fields are marked *