Lee Han Kyeol Lee Han Kyeol - 6 months ago 3x
PHP Question

What's the right format to create a PHP DateTime instance of '2016.04.30 PM 7:30' via DateTime::createFromFormat?

I'm currently working on a Wordpress project where I should get some custom post metadata, convert it to a

instance, and do the math with it.

When I
the get_post_meta, it looks as follows.

2016.04.30 PM 7:30

The format I'm using to get a
instance is as follows.

Y.m.d A g:i

But the return value of

// 2016.04.30 PM 7:30
$start_at = DateTime::createFromFormat( 'Y.m.d A g:i', get_post_meta(get_the_ID(), 'as_date', true));
if ($start_at === false) {
echo 'False format: ' . get_post_meta(get_the_ID(), 'as_date', true);
} else {
echo $start_at->getTimestamp();

The result is
False format: 2016.04.30 PM 7:30

What am I missing here? I think it must be something trivial but I can't get through.


Testing, I found that the problem character in the format was the 'A'. So I poked around and found this bug in PHP (that is apparently not a bug at all!)

Going through the source code, it looks like it will not parse AM and PM until after an hour has been already parsed.

Probably your best bet would be a quick pass through a regular expression to move the AM/PM to the end:

$thedate = get_post_meta(get_the_ID(), 'as_date', true);
$thedate = preg_replace("/([0-9.]+) ([ap]m) ([0-9:]+)/i", "$1 $3 $2", $thedate);
$start_at = DateTime::createFromFormat('Y.m.d g:i A', $thedate);