skip to Main Content

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


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

    Login or Signup to reply.
  2. 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 with str_replace(), then use strtotime() to convert it to an integer which you can then use to compare with your custom date. For example, using the date you provided:

    $date = strtotime(str_replace(',','','20 september, 2021'))
    

    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:

    $date = strtotime(str_replace(',','','20 september, 2021'));
    $current_date = str_replace(',','',date("D d, F Y"));
    
    if ($date < $current_date ) {
        echo "The date '$date' is less than today's date.";
    } else {
        echo "The date '$date' is not less than today's date.";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search