Converting Timestamp into a time ago in 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 '
';
echo converElapsedTime('2017-06-23 19:23:15');
echo '
';
echo converElapsedTime('2017-06-23 19:20:00');
echo '
';
echo converElapsedTime('2017-06-23 9:00:00');
echo '
';
echo converElapsedTime('2017-06-22');
echo '
';
echo converElapsedTime('2017-05-22');
echo '
';
echo converElapsedTime('2016-05-22');
echo '
';

The output for 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s