Monday 5 September 2016

Simple Time Ago Display Function in PHP

Make use of this simple function to display time ago format details of the time in your comment system. Facebook style time ago display script in simple php.

function timeAgo($date){
    $time = strtotime($date);
    $now = time();
    $ago = $now - $time;
    if($ago<60) {
        $timeago = round($ago);
        $s = ($timeago == 1)?"second":"seconds";
        return "$timeago $s ago";
    } elseif($ago<3600) {
        $timeago = round($ago / 60);
        $m = ($timeago == 1)?"minute":"minutes";
        return "$timeago $m ago";
    } elseif($ago>=3600 && $ago<86400) {
        $timeago = round($ago / 60 / 60);
        $h = ($timeago == 1)?"hour":"hours";
        return "$timeago $h ago";
    } elseif($ago>=86400 && $ago<2629743.83) {
        $timeago = round($ago / 60 / 60 / 24);
        $d = ($timeago == 1)?"day":"days";
        return "$timeago $d ago";
    } elseif($ago>=2629743.83 && $ago<31556926) {
        $timeago = round($ago / 60 / 60 / 24 / 30.4375);
        $m = ($timeago == 1)?"month":"months";
        return "$timeago $m ago";
    } else {
        $timeago = round($ago / 60 / 60 / 24 / 365);
        $y = ($timeago == 1)?"year":"years";
        return "$timeago $y ago";
    }
}

No comments:

Post a Comment