-1

Possible Duplicate:
Converting timestamp to time ago in php e.g 1 day ago, 2 days ago

I'm trying to display how old the post is through php. What I'm doing is storing in mysql the php timestamp using the code below.

$timestamp=time();

So then I'm left with a number like this

1334216865

How would I go about changing it so it will say example:

8 seconds ago

If you refresh the page 10 seconds later it will show:

18 seconds ago

I'm not sure how I would convert a timestamp back into time to show my examples.

Thank you

Community
  • 1
  • 1
Tabatha M
  • 171
  • 2
  • 6
  • 13
  • 1
    Hint: A timestamp is *the number of seconds since Jan. 1st 1970.* The difference between now and the timestamp of one second later is exactly 1... – deceze Apr 12 '12 at 07:01

3 Answers3

6

Or you could make a little "time_ago" function:

function ago($time) { 
    $timediff=time()-$time; 

    $days=intval($timediff/86400);
    $remain=$timediff%86400;
    $hours=intval($remain/3600);
    $remain=$remain%3600;
    $mins=intval($remain/60);
    $secs=$remain%60;

    if ($secs>=0) $timestring = "0m".$secs."s";
    if ($mins>0) $timestring = $mins."m".$secs."s";
    if ($hours>0) $timestring = $hours."u".$mins."m";
    if ($days>0) $timestring = $days."d".$hours."u";

    return $timestring; 
}
echo ago(1334214962);
Gert Van de Ven
  • 997
  • 6
  • 6
  • Awesome library, didn't even read the source code just dropped it in. Love it. Nailed it. Thanks. – Andy May 02 '19 at 03:16
4
echo (time() - $post_timestamp) . " seconds ago";

very simple.

castor
  • 585
  • 2
  • 8
2

Just run the time() function again and subtract the posted time - then do some arithmetic to output how long it has been: 60 seconds per minute, 60 minutes per hour,etc... the time function is how many seconds since some event a long time ago. so, every increment is 1 second on the time function.

Emery King
  • 3,550
  • 23
  • 34