Creating TimeAgo function in PHP

Many times while displaying time on website we need to do something extra.

This function script can give you time in days/hour/minutes/seconds ago format.

You just need to pass the mysql time to this function. like this:

echo timeago("2013-11-24 18:00:09");
function timeago($timeStr) {
    $time = strtotime($timeStr);
    
    $output = "";
    $time_difference = time() - $time; 
    $seconds = $time_difference ; 
    $minutes = round($time_difference / 60 );
    $hours = round($time_difference / 3600 ); 
    $days = round($time_difference / 86400 ); 
    $weeks = round($time_difference / 604800 ); 
    $months = round($time_difference / 2419200 ); 
    $years = round($time_difference / 29030400 ); 
    
    if($seconds <= 60) {
        // Seconds
        $output = "$seconds seconds ago"; 
    } else if($minutes <=60) {
        //Minutes
        if($minutes==1) {
            $output = "one minute ago"; 
        } else {
            $output = "$minutes minutes ago"; 
        }
    } else if($hours <=24) {
        //Hours
        if($hours==1) {
            $output = "one hour ago";
        } else {
            $output = "$hours hours ago";
        }
    } else if($days <= 7) {
        //Days
        if($days==1) {
            $output = "one day ago";
        } else {
            $output = "$days days ago";
        }
    } else if($weeks <= 4) {
        //Weeks
        if($weeks==1) {
            $output = "one week ago";
        } else {
            $output = "$weeks weeks ago";
        }
    } else if($months <=12) {
        //Months
        if($months==1) {
            $output = "one month ago";
       } else {
            $output = "$months months ago";
       }
    } else {
        //Years
        if($years==1) {
            $output = "one year ago";
        } else {
            $output = "$years years ago";
        }
    }
    return $output;
}

Note: sometimes you may get time error while using this function because of timezone.
In such case you might need to correct time difference by subtracting the difference from time-stamp. You jst need to modify the first line of function by $time = strtotime($timeStr) - 37800;. where 37800 is time difference in milliseconds.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.