1

I am trying to show the time in format of like: few sec ago, 5 min ago, 2 days ago etc. I searched and find some piece of code, and make it workable.

ISSUE

It is not showing the result correct.When i made a post it show the just "NOW" if it has been 2 minutes and so on.

"Code"`

define( "TIMEBEFORE_NOW",         'now' );
define( "TIMEBEFORE_MINUTE",      '{num} minute ago' );
define( "TIMEBEFORE_MINUTES",     '{num} minutes ago' );
define( "TIMEBEFORE_HOUR",        '{num} hour ago' );
define( "TIMEBEFORE_HOURS",       '{num} hours ago' );
define( "TIMEBEFORE_YESTERDAY",   'yesterday' );
define( "TIMEBEFORE_FORMAT",      '%e %b' );
define( "TIMEBEFORE_FORMAT_YEAR", '%e %b, %Y' );

function time_ago( $time )
{
    $out    = ''; // what we will print out
    $now    = time(); // current time
    $diff   = $now - strtotime($time); // difference between the current and the provided dates

    if( $diff < 60 ) // it happened now
        return TIMEBEFORE_NOW;

    elseif( $diff < 3600 ) // it happened X minutes ago
        return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES );

    elseif( $diff < 3600 * 24 ) // it happened X hours ago
        return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS );

    elseif( $diff < 3600 * 24 * 2 ) // it happened yesterday
        return TIMEBEFORE_YESTERDAY;

    else // falling back on a usual date format as it happened later than yesterday
        return strftime( date( 'Y', strtotime($time)) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, strtotime($time));
}

?>`

usage

Posted on <span style="font-style: italic;">
          <time datetime="<?php strftime(date('Y-m-d', strtotime($posts->Time)));?>" 
    title="<?php strftime(date( 'Y', strtotime($posts->Time)) == date('Y') ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR,strtotime($posts->Time))?>">
    <?php echo time_ago($posts->Time);?>
    </time>

Any help will be appreciated.

0 Answers0