-1

i'm looking for a PHP code to change time like this: Fri Jul 16 16:58:46 +0000 2010 to a timestamp like this: 20 secs ago

Any help will be appreciated

gamehelp16
  • 1,101
  • 1
  • 7
  • 22
  • also http://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago?rq=1 – Gordon May 25 '13 at 07:20

3 Answers3

3

Use the strtotime() function and then compare it to the current time:

$timestamp = strtotime( 'Fri Jul 16 16:58:46 +0000 2010' );

$diff = time() - $timestamp;

This gives you the difference to the current time and you can output it in the way you need.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • only after a while, you might see `2817646532 seconds ago`. a more robust library is needed I believe. – Sagish May 25 '13 at 06:40
  • @SagiIsha I left out the output part on purpose :-) But you're right, one has to put some thought to that as well. – Sirko May 25 '13 at 06:41
2

Try with strtotime like

$my_time = strtotime('Fri Jul 16 16:58:46 +0000 2010');
$diff = time() - $my_time;
echo $diff." Seconds ago..";

you can get the minutes and hours as well like

echo $diff/60."Minutes Ago";
echo $diff/(60*60)."Hours Ago";

Totally you can use

$a = array( 12 * 30 * 24 * 60 * 60  =>  'year',
            30 * 24 * 60 * 60       =>  'month',
            24 * 60 * 60            =>  'day',
            60 * 60                 =>  'hour',
            60                      =>  'minute',
            1                       =>  'second'
            );

foreach ($a as $secs => $str) {
    $d = $diff / $secs;
    if ($d >= 1) {
        $r = round($d);
        echo $r . ' ' . $str . ($r > 1 ? 's' : '').' ago..';
    }
}
GautamD31
  • 28,552
  • 10
  • 64
  • 85
1

You should use a robust library to handle this, so you can estimate not only seconds but hours, days, weeks, months etc, when the time elapses as long. See i.e http://github.com/jimmiw/php-time-ago

Sagish
  • 1,065
  • 8
  • 13
  • or you could use the built-in DateTime and DateInterval classes: http://www.php.net/manual/en/class.dateinterval.php – HorusKol May 25 '13 at 07:00