Dirty Bird Design
Dirty Bird Design

Reputation: 5553

How to format date with value returned as variable in PHP

Im working on a WP site using WP Download Manager Pro. I am able to access the object's date like this:

<?php $packageID = get_field('user_submitted_app_download_id'); $post_date = $package['post_date'];?>

It is returning the date like this "2018-01-03 10:56:11" I need to re-arrange it so it posts like this "03-01-2018" -> m-d-Y

I keep getting errors and don't know what I'm doing wrong. From PHP.net -

<?php $post_date = $package['post_date']; echo date_format($post_date, m-d-Y); ?>

I get this laundry list of errors:

Notice: Use of undefined constant m - assumed 'm' in /home/ntecosys/sandboxwp2/wp-content/plugins/facetwp/includes/class-renderer.php(467) : eval()'d code on line 18

Notice: Use of undefined constant d - assumed 'd' in /home/ntecosys/sandboxwp2/wp-content/plugins/facetwp/includes/class-renderer.php(467) : eval()'d code on line 18

Notice: Use of undefined constant Y - assumed 'Y' in /home/ntecosys/sandboxwp2/wp-content/plugins/facetwp/includes/class-renderer.php(467) : eval()'d code on line 18

Warning: date_format() expects parameter 1 to be DateTimeInterface, string given in /home/ntecosys/sandboxwp2/wp-content/plugins/facetwp/includes/class-renderer.php(467) : eval()'d code on line 18

How do I reformat the date?

Upvotes: 0

Views: 533

Answers (2)

cpilko
cpilko

Reputation: 11852

Your $post_date is a string, and date_format() expects a DateTime Object.

This is the shorter way, converting your string to a unix timestamp:

echo date('m-d-Y' strtotime($post_date)); 

Otherwise you'll need to use date_create_from_format to parse your string into an object that you can manipulate with date_format, but that's a lot more verbose.

Upvotes: 1

William Tran
William Tran

Reputation: 699

I believe you have to wrap your date format in quote

echo date_format($post_date, 'm-d-Y');

Upvotes: 1

Related Questions