Home Forums General Issues Echo date picker field returns fatal error


Echo date picker field returns fatal error

  • Hi,

    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 'ljFY'?

    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.

    $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.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Echo date picker field returns fatal error’ is closed to new replies.