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.
The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.
A few examples of creating DateTime objects with valid time string: $yesterday = new DateTime('yesterday'); $twoDaysLater = new DateTime('+ 2 days'); $oneWeekEarly = new DateTime('- 1 week'); The second parameter of the DateTime's constructor allows us to specify a timezone.
Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400) c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00) r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
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);
Change the date format and try createFromFormat
$non_standard_format = '2016.04.30 PM 7:30';
$non_standard_format = str_replace('.','-',$non_standard_format);
$date_components = explode(" ",$non_standard_format);
$standard_format = $date_components[0]." ".$date_components[2]." ".$date_components[1];
Then try passing this to DateTime::createFromFormat
$start_at = DateTime::createFromFormat( 'Y-m-d g:i A', $standard_format);
if ($start_at === false) {
echo 'False format: ' . get_post_meta(get_the_ID(), 'as_date', true);
} else {
echo $start_at->getTimestamp();
}
Supported date formats in PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With