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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s