What is the correct format for creating a PHP DateTime instance of '2016.04.30 PM 7:30' via DateTime :: createFromFormat?

I am currently working on a Wordpress project where I need to get some personalized message metadata, convert it to an DateTime instance and do the math with it.

When I echo get_post_meta, it looks like this.

2016.04.30 7:30

The format that I use to get an instance of DateTime is as follows.

Ymd A g: i

But the return value of DateTime::createFromFormat is false .

 // 2016.04.30 PM 7:30 $start_at = DateTime::createFromFormat( 'Ymd 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(); } 

Result False format: 2016.04.30 PM 7:30 .

What am I missing here? I think it should be something trivial, but I can’t get through.

+6
source share
2 answers

Testing, I found that the nature of the problem in the format was "A". So I poked and found this error in PHP (this is apparently not an error!)

Looking through the source code , it looks like it will not parse AM and PM until it is parsed in an hour.

Probably the best option would be to quickly go through the regex to move 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('Ymd g:i A', $thedate); 
+3
source

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( 'Ymd 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

+1
source

All Articles