Converting Timestamp into a time ago in PHP.

  • 14 July, 2018
  • Renish Khunt
  • PHP

How can we display the published date into a time ago like ‘a second ago’, ‘a minute ago’, ‘days ago’, ‘a month ago’, ‘a year ago’. So we did this using simple function let’s copy below function and past it with your code.

<?php

function converElapsedTime( $datetime, $full = false )
{
    $now = new DateTime;
    $then = new DateTime( $datetime );
    $diff = (array) $now->diff( $then );

    $diff['w']  = floor( $diff['d'] / 7 );
    $diff['d'] -= $diff['w'] * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );

    foreach( $string as $k => & $v )
    {
        if ( $diff[$k] )
        {
            $v = $diff[$k] . ' ' . $v .( $diff[$k] > 1 ? 's' : '' );
        }
        else
        {
            unset( $string[$k] );
        }
    }

    if ( ! $full ) $string = array_slice( $string, 0, 1 );
    return $string ? implode( ', ', $string ) . ' ago' : 'just now';
}

let’s see how to use above function for displaying the date like “a minute ago”.

echo "Curren Time : ".date("Y-m-d H:i:s"); 
echo '<br>';
echo converElapsedTime('2017-06-23 19:23:15');
echo '<br>';
echo converElapsedTime('2017-06-23 19:20:00');
echo '<br>';
echo converElapsedTime('2017-06-23 9:00:00');
echo '<br>';
echo converElapsedTime('2017-06-22');
echo '<br>';
echo converElapsedTime('2017-05-22');
echo '<br>';
echo converElapsedTime('2016-05-22');
echo '<br>';

The output of above code is below.

Curren Time : 2017-06-23 19:23:20
5 seconds ago
3 minutes ago
10 hours ago
1 day ago
1 month ago
1 year ago

See the output just used above function for display the published time like ‘a minute ago’.

You face any issue after using the above code just write the comment.