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.
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.
Share Improve this question asked May 12, 2020 at 5:25 RubenGeertRubenGeert 3972 gold badges3 silver badges11 bronze badges 2 |1 Answer
Reset to default 2If 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.
post_date_gmt
in your site's timezone? – Jacob Peattie Commented May 12, 2020 at 5:37