Home › Forums › General Issues › Echo date picker field returns fatal error
I’m trying to echo the value of a date picker field which is formatted as DD d MM yy (JS date format). If I’m correct that should be l j F Y in PHP format.
However when I try to echo the date in my loop it returns a fatal error:
Fatal error: Call to a member function format() on a non-object
It’s referring to the following line in my code:
<?php $date = DateTime::createFromFormat('ljFY', get_field('datum')); ?>
The full code to echo the date is as follow:
<?php if(get_field('datum')): ?> <?php $date = DateTime::createFromFormat('ljFY', get_field('datum')); ?> <?php echo $date->format('l j F Y');?> <?php endif; ?>
I’ve used the same code with only a different date format without any problems. However this times it returns a fatal error. But why? I’m 99.9% sure that I’ve used the correct PHP date format.
Is the return format of your date field
The return value of your date field must precisely match the date format you use in
$date = DateTime::createFromFormat('ljFY', get_field('datum'));
My question is, if this is the format that you want your date displayed in why not simply set the return format to this in the settings for the field?
Well I finally solved it by changing the store format to yymmdd. After that I could use the code example from the documentation like this.
$date = DateTime::createFromFormat('Ymd', get_field('date_picker')); echo $date->format('d-m-Y');
I changed the output value to
j F Y but then found out that the output was English even though it was displayed in Dutch in the WP admin area. But well that was easily sorted with the translation snipper from the documentation.
<?php $dateformatstring = "l d F, Y"; $unixtimestamp = strtotime(get_field('date_picker')); echo date_i18n($dateformatstring, $unixtimestamp); ?>
So in the end I didn’t even have to use my code that was causing the error and was making it too complicated for myself when I could use the code examples. But well, I learned something again as this was my first usage of the date picker field.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 2023 Advanced Custom Fields.