PHP Time Ago functionality is used to display time in a different format.



  • Display the time format, which is easy to understand.
  • Display the time format similar to different time zone.
  • It is commonly used in messaging and feeds.

Time Ago Implementation

It takes the timestamp as input and subtracts it with the current timestamp. Then it compares the remaining date with a predefined set of rules which determine the month, day, minute, and even year. Then it calculates time difference by using a predefined set of rules which determine the second, minute, hour, day, month, and year.

Time Ago Function


function get_time_ago( $time )
{
    $time_difference = time() - $time;

    if( $time_difference < 1 ) { return 'less than 1 second ago'; }
    $condition = array( 12 * 30 * 24 * 60 * 60 =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
    );

    foreach( $condition as $secs => $str )
    {
        $d = $time_difference / $secs;

        if( $d >= 1 )
        {
            $t = round( $d );
            return 'about ' . $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago';
        }
    }
}

Calling the Function

PHP Example:

echo get_time_ago( time()-5 ).'<br>';
echo get_time_ago( time()-60 ).'<br>';
echo get_time_ago( time()-3600 ).'<br>';
echo get_time_ago( time()-86400 ).'<br>';
echo get_time_ago( time()-2592000 ).'<br>';
echo get_time_ago( time()-31104000 ).'<br>';
echo "---".'<br>';
echo get_time_ago( strtotime("2013-12-01") );

Output:

about 5 seconds ago
about 1 minute ago
about 1 hour ago
about 1 day ago
about 1 month ago
about 1 year ago
---
about 2 years ago



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram