TimeAgo function in PHP

This can be used for comments and other from of communication to tell the time ago instead of the exact time which might not be correct to some one in another time zone.

The function only uses unix time stamp like the result of time();

function timeago($time) {
        $time = strtotime($time);
        $periods = array(L('second'), L('minute'), L('hour'), L('day'), L('week'), L('month'), L('year'), L('decade'));
        $periodsPlural = array(L('seconds'), L('minutes'), L('hours'), L('days'), L('weeks'), L('months'), L('years'), L('decades'));
        $lengths = array("60","60","24","7","4.35","12","10");

        $now = time();

        $difference     = $now - $time;
        $tense         = L('ago');

        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)
        {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        if($difference != 1)
        {
            return "$difference $periodsPlural[$j] $tense";
        } else {
            return "$difference $periods[$j] $tense";
        }
    }

Needs a time() value, and it will tell you how many seconds/minutes/hours/days/years/decades ago.

Advertisements