0

I want to get time difference like "posted 2 days ago".

I know you can use the following to get the difference.

human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago';

But I don't want to use that

        date_default_timezone_set('Australia/Melbourne'); // set the time zone
        $timestamp = strtotime( $post->post_date ); // get timestamp
        $now =  time();// get the curren time
        $time_passed = $timestamp - $now; // get the differnece

    // display time
    $min = $time_passed / 60;
    if( $min < 60 ) {
        return sprintf( avantgardia__( '%s min. ago', 'newspeak' ), intval( $min) );
    }
  • human_time_diff() does display "2 days", the post just needs to be older than a day, and less than a week. Or do you only want to display days? So "posted 0 days ago", and "posted 1303 days ago"? – Jacob Peattie Oct 16 '18 at 1:09
  • @JacobPeattie Yeah so skip mins, hour. so If a post is 30mins old then show "0 days old" – Mais_Cule Oct 16 '18 at 1:30
1

Try the date_diff() / DateTime::diff() function in PHP:

// Object-oriented style.
$datetime1 = new DateTime( $post->post_date );
$datetime2 = new DateTime(); // current date
$interval = $datetime1->diff( $datetime2 );
echo $interval->format( '%a days old' );

// .. or procedural style.
$datetime1 = date_create( $post->post_date );
$datetime2 = date_create(); // current date
$interval = date_diff( $datetime1, $datetime2 );
echo $interval->format( '%a days old' );

In PHP 5.2.2 or later, you can compare the date ("ago" vs "later") like so:

if ( $datetime1 < $datetime2 ) {
    echo $interval->format( 'Published %a days ago.' );
} elseif ( $datetime1 > $datetime2 ) {
    echo $interval->format( 'Will be published in %a days later.' );
} else {
    echo 'Published today.';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.