0

I'd like to find the time difference -preferably in hours- between post_date and post_date_gmt.

I tried $age = date_diff(get_post_time(),get_post_time($gmt = true));

but this returns

Warning: date_diff() expects parameter 1 to be DateTimeInterface, int given in C:\xampp\htdocs\t\wp-content\themes\i\single.php on line 23

I didn't really understand the official WP documentation on this function -do they refer to just "time" or "timestamps"?

The basic reason is that I abused the post_date to store the last update date while the gmt field still contains the original publication date. I know that's wrong but I needed a quick and dirty solution some time ago for a different problem.

2
  • So is your ultimate goal to display post_date_gmt in your site's timezone? – Jacob Peattie May 12 '20 at 5:37
  • No. The difference between these 2 timestamps tells me if a post was updated or just published. If the difference is less than 24 hours, it's never been updated. – RubenGeert May 12 '20 at 6:01
2

If all you need to do is check the difference, rather than display or modify anything, then you don't need to do anything complicated with date_diff(). All you need to do is compare the number of seconds returned by get_post_time() for each date.

get_post_time() returns the Unix timestamp for the date, which is simply the number of seconds since January 1 1970. So if the difference between the two timestamps is greater than 86400 seconds, the difference is greater than 24 hours.

$difference = get_post_time( 'U', true ) - get_post_time( 'U', false );

if ( $difference > DAY_IN_SECONDS ) {
    // GMT date is over 24 hours more than post date.
}

The 'U' in this code tells get_post_time() to return the value as a Unix timestamp. It's the default value, but we need to set it to be able to set the second argument, which tells it whether to use the post_date or post_date_gmt.

In this example DAY_IN_SECONDS is a WordPress constant equal to 86400. Using it makes the code more readable, and you don't have to figure out what the number was supposed to mean later.

1
  • Thanks a lot man! The whole thing is working perfectly and your explanation is much more helpful than the official documentation! – RubenGeert May 12 '20 at 13:01

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.