I am trying to retrieve my 2 dates (start date and end date) and to get the difference between them in the same format in wordpress.
My ACF DatePicker fields return:
j F, Y
format that is 20 september, 2021
I tried with the ACF method , but it gives me an error..
$start_date = get_field('start_date');
$date = DateTime::createFromFormat('j F, Y', $start_date);
echo $date->format('j F, Y');
Uncaught Error: Call to a member function format() on bool
Why it doesn’t work ?
2
Answers
It’s possible the return type is not set correctly for the ACF ‘start_time’ field. Might be worth checking this in the custom fields settings.
The other thing you can try is wrapping the get_field(“start_time”) in a strtotime() function before passing it to the formatted.
See this for an idea. https://stackoverflow.com/a/6239010/4172254
Comparing the dates will work if you convert the date to an integer. However, you would need to remove the
,
from the the date string withstr_replace()
, then usestrtotime()
to convert it to an integer which you can then use to compare with your custom date. For example, using the date you provided:Note
You would also need to convert the custom date to an integer using the same process above if you wish to both dates.
For example, comparing the above date to today’s date would look like this: