Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display "12 minutes ago" etc in a PHP webpage? [closed]

Tags:

php

Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?

like image 774
Niyaz Avatar asked Aug 20 '08 19:08

Niyaz


3 Answers

Here is the php code for the same:

function time_since($since) {
    $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 , 'minute'),
        array(1 , 'second')
    );

    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

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

The function takes the number of seconds as input and outputs text such as:

  • 10 seconds
  • 1 minute

etc

like image 150
Niyaz Avatar answered Nov 18 '22 06:11

Niyaz


function timeAgo($timestamp){
    $datetime1=new DateTime("now");
    $datetime2=date_create($timestamp);
    $diff=date_diff($datetime1, $datetime2);
    $timemsg='';
    if($diff->y > 0){
        $timemsg = $diff->y .' year'. ($diff->y > 1?"'s":'');

    }
    else if($diff->m > 0){
     $timemsg = $diff->m . ' month'. ($diff->m > 1?"'s":'');
    }
    else if($diff->d > 0){
     $timemsg = $diff->d .' day'. ($diff->d > 1?"'s":'');
    }
    else if($diff->h > 0){
     $timemsg = $diff->h .' hour'.($diff->h > 1 ? "'s":'');
    }
    else if($diff->i > 0){
     $timemsg = $diff->i .' minute'. ($diff->i > 1?"'s":'');
    }
    else if($diff->s > 0){
     $timemsg = $diff->s .' second'. ($diff->s > 1?"'s":'');
    }

$timemsg = $timemsg.' ago';
return $timemsg;
}
like image 26
Dipesh Avatar answered Nov 18 '22 07:11

Dipesh


PHP's \DateTime::diff returns a \DateInterval object on which you can get the minutes by the public i property.

like image 6
Sebastiaan Hilbers Avatar answered Nov 18 '22 06:11

Sebastiaan Hilbers