Reputation: 23
I am using meta_box value (YmdHi)
and current Date&time
to print time difference. And this code work for me.
Now additionally i want to print Live
when 2 hours left to start Event.
What mistake I 'm doing to print if or else
currently this not work for me?
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
if ($sinceThen > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}
Upvotes: 2
Views: 93
Reputation: 9957
$sinceThen
is a DateInterval
(that's what DateTime::diff()
returns), so you're comparing a int
with an object
, which obviously gives you unexpected results. To get the difference in seconds, subtract both DateTime
instances' timestamps (which you obtain with DateTime::getTimestamp()
):
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
$sinceThenInSeconds = $then->getTimestamp() - $now->getTimestamp();
if ($sinceThenInSeconds > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}
Upvotes: 1