I’m trying to get the difference between a date and current date but always returns 0.
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00 $start_date = new DateTime($start_date); $date_now = new DateTime(); if ($date_now > $start_date){ $diff = date_diff($date_now, $start_date); } echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds");
Advertisement
Answer
The issue seems to be that $date_now
is less than $start_date
, so the code inside of the if
block never runs. As such $diff
is undefined. This should be throwing an error, which might have helped you suss this out – but sometimes error reporting is turned off. You might want to set up a local testing environment where error reporting is enabled, I’d bet you get to the bottom of this in no time. 🙂
What you might be wanting is something closer to this:
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00 $start_date = new DateTime($start_date); $date_now = new DateTime(); $diff = date_diff($date_now, $start_date); $time_from_str = $diff->invert ? "ago" : "until" echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds") . " " . $time_from_str;
This always gets the interval of time, but adds some context for the end user to know if the time is in the past or the future.
Or, if you want to hard-stop at the start_date (which is implied by the id statement), you could do:
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00 $start_date = new DateTime($start_date); $date_now = new DateTime(); if($date_now > $start_date) { $diff = date_diff($date_now, $start_date); } else { $diff = new DateInterval("P0Y"); // an empty time interval, just so $diff is still defined } echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds");
Hope that’s helpful. Good luck!