I’m currently working on a WordPress project where I should get some custom post metadata, convert it to a DateTime
instance, and do the math with it.
When I echo
the get_post_meta, it looks as follows.
2016.04.30 PM 7:30
The format I’m using to get a DateTime
instance is as follows.
Y.m.d A g:i
But the return value of DateTime::createFromFormat
is false
.
// 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:
Change the date format and try
createFromFormat
Then try passing this to
DateTime::createFromFormat
Supported date formats in PHP