Saturday, December 20, 2014

How to Create Article Post Time Ago Function in PHP

Get the function to create article post time ago function with using simple PHP codes. The function counts the time differences in words. Most of the popular sites use this function to show the time. For example :- It shows 15 minutes ago.

Article Post Time Ago Function in PHP


Create a simple Function  :- 

function timeAgo($ptime) {
    $setime = time() - $ptime;
   
    if ($setime < 1) {
        return '0 seconds';
    }
   
    $interval = array( 12 * 30 * 24 * 60 * 60  =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
                );
   
    foreach ($interval as $secs => $str) {
        $d = $setime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . ' ' . $str . ($r > 1 ? 's' : '');
        }
    }
}

Use the below code snippets :-

$t=time()-600;
echo time_ago($t);  //outputs => 10 mins

$t=time()-3600;
echo time_ago($t);  //outputs => 1 hour

$t=time()-86400 * 65;
echo time_ago($t);  //outputs => 2 months

Reference :- http://freewebmentor.com/2014/11/create-article-post-time-ago-function-php.html

0 comments:

Post a Comment