Jackson Siro Jackson Siro - 29 days ago 6
PHP Question

How to fix Timeago errors

I have a time ago function in php which i use to return if the user is online or when the user was last seen.

function tj_online_last($ptime) {
$estimate_time = time() - strtotime($ptime);
// if time diff is less than 1 minute then user is online
if ($estimate_time < 60) {
return 'online';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second',
);
foreach($condition as $secs => $str) {
$d = $estimate_time / $secs;
if ($d >= 1) {
$r = round($d);
return $r.' '.$str.($r > 1 ? 's' : '').' ago';
}
}
}


Now the problem here when the user has not been logged into his account for the first time the time value is 'NULL'. I would like to return 'never' instead of the annoying '48 years ago' because I am not able to handle the error.

Answer

Try this... When user first time login then it's last entry is null so you need to check condition if last date is empty then return 'never';

function tj_online_last($ptime) {
    if(strtotime($ptime) <= 0){
        return 'never';
    }
    $estimate_time = time() - strtotime($ptime);
    // if time diff is less than 1 minute then user is online
    if ($estimate_time < 60) {
        return 'online';
    }
    $condition = array(
                12 * 30 * 24 * 60 * 60   => 'year',
                30 * 24 * 60 * 60        => 'month',
                24 * 60 * 60             => 'day',
                60 * 60                  => 'hour',
                60                       => 'minute',
                1                        => 'second',
    );
    foreach($condition as $secs => $str) {
        $d = $estimate_time / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r.' '.$str.($r > 1 ? 's' : '').' ago';
        } 
    }
}
Comments