How to: Create facebook or twitter style “x-time ago” date format in php

Normally date formats are like “ January 1 2010 10:40:25 GMT” , “01 Mar 2010” . etc . But here I tell you ‘how to show date like “1 minutes ago” , “2 days ago” , displayed in Facebook , Twitter etc..

In php time(); function returns a Unix Value of current date and time like 123454487 . We can convert Unix value to readable date format using date(); function.

Here is the simple php code for display date as Twitter or Facebook style .

function ShowDate($date) // $date -->  time(); value
{
$stf = 0;
$cur_time = time();
$diff = $cur_time - $date;
$phrase = array('second','minute','hour','day','week','month','year','decade');
$length = array(1,60,3600,86400,604800,2630880,31570560,315705600);

for($i =sizeof($length)-1; ($i >=0)&amp;&amp;(($no =  $diff/$length[$i])< =1); $i--); if($i < 0) $i=0; $_time = $cur_time  -($diff%$length[$i]);
$no = floor($no); if($no <> 1) $phrase[$i] .='s'; $value=sprintf("%d %s ",$no,$phrase[$i]);

if(($stf == 1)&amp;&amp;($i >= 1)&amp;&amp;(($cur_tm-$_time) > 0)) $value .= time_ago($_time);

return $value.' ago ';
}

WordPress users please use this code :

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

If you have any feedback, bug reports please comment below. Happy coding :)

Please note: comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.
* **
*
* Required. **will not be published.

  1. sajooo Sep 8, 2011

    i think the problem is here…
    for($i =sizeof($length)-1; ($i >=0)&&(($no = $diff/$length[$i])< =1); $i–); if($i < 0) $i=0; $_time = $cur_time -($diff%$length[$i]);
    &&

    im wating please help me…

  2. sajooo Aug 8, 2011

    dear i tried your script but browser throw and error like this.
    Parse error: parse error, expecting `’)” in C:\wamp\www\crawl\testing.php on line 11.

    i also change “&amp” to “&”. but the still a parse error kindly help me im beginner.

    Thanx in advance…

  3. Hi…
    I have downloaded this script, and it’s given me an error on line 18. Would you please help me find the error?

    • lineshjose Jul 16, 2011

      Hi Dana,

      Please change the “&amp” to “&” in the script and try again

  4. Novriyandie Jan 23, 2011

    help me! How do I use in my blogspot? I am a beginner

  5. Guall Ceance Nov 14, 2010

    Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  6. Thanks dude……
    this is the code I’m looking for.