Convert timestamp to time ago in PHP CodeIgniter helper

This CodeIgniter tutorial is for converting given date into a time ago string like Just Now, 2 hours age, 3 years ago etc.

Given a time and the task is to convert timestamp to time ago. The time ago format removes the problem of different time zones conversions. Given below is a function to do the time conversions. In this function, taking the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format. To make this function, need to define some rules which determine the year, month, date, minutes etc from the remaining date after subtraction.

Create a helper file for time ago function. Go to application/helpers folder and create the custom_helper.php file and add the code given below.

Now Open config file from location application/config/autoload.php and Find

$autoload['helper'] = array();

Now replace from below code

$autoload['helper'] = array('custom');

Now add below Code in custom_helper.php

function time_ago($timestamp) {
    $time_ago = strtotime($timestamp);
    $current_time = time();
    $time_difference = $current_time - $time_ago;
    $seconds = $time_difference;
    $minutes = round($seconds / 60);
    $hours = round($seconds / 3600);
    $days = round($seconds / 86400);
    $weeks = round($seconds / 604800);
    $months = round($seconds / 2629440);
    $years = round($seconds / 31553280);

    if ($seconds <= 60) {
        return "Just Now";
    } else if ($minutes <= 60) {
        if ($minutes == 1) {
            return "1 " . "minute ago";
        } else {
            return $minutes . " " . "minutes ago";
        }
    } else if ($hours <= 24) {
        if ($hours == 1) {
            return "1 " . "hour ago";
        } else {
            return $hours . " " . "hours ago";
        }
    } else if ($days <= 30) {
        if ($days == 1) {
            return "1 " . "day ago";
        } else {
            return $days . " " . "days ago";
        }
    } else if ($months <= 12) {
        if ($months == 1) {
            return "1 " . "month ago";
        } else {
            return $months . " " . "months ago";
        }
    } else {
        if ($years == 1) {
            return "1 " . "year ago";
        } else {
            return $years . " " . "years ago";
        }
    }
}

Calling the function in view file

<?php foreach ($latest_posts as $post);
 echo time_ago($post->created_at);
endforeach; ?>
RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply