Skip to content
Advertisement

wordpress date format change function

I am using below function getting dates from advanced custom fields pro plugin

my below code displays the dates from options ,

i want date format is different

 <!--event_start_date-->
            <?php if( get_field('event_start_date') ): ?>
            Event start date:
            <?php the_field('event_start_date'); ?><br/>
            <?php endif; ?>

            <!--Event end date-->
            <?php if( get_field('event_end_date') ): ?>
            Event end date:
            <?php the_field('event_end_date'); ?><br/>
            <?php endif; ?>

i have used below code to change the format but not working , here the_field('event_start_date'); directly displaying without print/echo

$new_date = date("d-M-Y", strtotime(the_field('event_start_date')));
echo $new_date;

Advertisement

Answer

A direct way is to use ob_get_clean() to capture the output, like this:

<!--Event end date-->
<?php if( get_field('event_start_date') ): ?>
Event end date:

<?php 
ob_start();

the_field('event_start_date');
$date_string = ob_get_clean();
$new_date = date("d-M-Y", strtotime($date_string));
echo $new_date;    
?>
<br/>
<?php endif; ?>

This is a bit overkill. Its best if you can find a function in the plugin that returns the data rather than outputs it.

Looking through the documentation for acf plugin, the function get_field() does this.

According to the acf documentation, the date is stored a bit differently. https://www.advancedcustomfields.com/resources/date-picker/

$date_string = get_field('event_start_date',false,false)
$date = new DateTime($date_string);
$new_date = $date->format('d-M-Y');
echo $new_date;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement