wordpress - date_format() in PHP not returning the formatted date

150

Thedate_format function is not returning the formatted value of the variable but instead the current date only

I have tried different date variables and formats but to no avail. This is done in WordPress environment.

....

 <span class="some-css-class">
  <?php
   $eventDate = new DateTime(the_field('date_event'));
   //'event_date is the name of the date time field created for the post
   echo date_format($eventDate,'M'); 
  ?>
  </span>

....

I have tried different variables and number formats. Searched for WordPress environment specific solutions but none works. The result shows today's date being formatted instead of the given date.

The result shows the date of the event in non-formatted form and today's date in formatted form.

221

Answer

Solution:

The result shows today's date being formatted instead of the given date.

That’s because you are not giving any date to the DateTime constructor here - so it defaults to today.

$eventDate = new DateTime(the_field('date_event'));

the_field outputs the value directly. You want to pass the value as a parameter into the DateTime constructor, so you need to use the function that returns the value instead of outputting it directly -get_field.

People are also looking for solutions to the problem: php - How to get the website name based on whether the website supports http or https?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.