PHP program to convert a given timestamp into time ago

In PHP, converting a timestamp to a human-readable "time ago" format is useful for displaying relative time in applications like social media feeds or comment systems. This can be achieved using a custom function that calculates the time difference and formats it appropriately.

Example

The following example demonstrates how to convert a timestamp into a "time ago" format ?

<?php
function to_time_ago($time)
{
    $difference = time() - $time;
    if($difference < 1)
    {
        return 'less than a second ago';
    }
    
    $time_rule = array (
        12 * 30 * 24 * 60 * 60 => 'year',
        30 * 24 * 60 * 60 => 'month',
        24 * 60 * 60 => 'day',
        60 * 60 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    
    foreach($time_rule as $sec => $my_str)
    {
        $res = $difference / $sec;
        if($res >= 1)
        {
            $t = round($res);
            return $t . ' ' . $my_str . ($t > 1 ? 's' : '') . ' ago';
        }
    }
}

echo "The timestamp to time ago conversion is ";
echo to_time_ago(time() - 600);
echo "<br>";
echo to_time_ago(time() - 3661);
echo "<br>";
echo to_time_ago(time() - 86400);
?>
The timestamp to time ago conversion is 10 minutes ago
1 hour ago
1 day ago

How It Works

The to_time_ago() function calculates the difference between the current time and the given timestamp. It uses an array of time intervals (from years to seconds) and finds the largest applicable unit. The function handles pluralization automatically by adding "s" for values greater than 1.

Conclusion

This approach provides a flexible way to display relative timestamps in a user-friendly format. The function can be easily customized to include additional time units or different formatting styles as needed.

Updated on: 2026-03-15T09:04:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements