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 DateTime instance, and do the math with it.

When I echo the get_post_meta, it looks as follows.

Read More

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.

Related posts

2 comments

  1. 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);
    
  2. 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

Comments are closed.