Skip to content
Advertisement

How convert this date: “16/11/2020 12:00:00 a. m.” to “2020-11-16 00:00:00” with PHP?

Currently, I am requesting an external web service to get some important information. However, the dates this web services return me are something like this:

16/11/2020 12:00:00 a. m.

So, I was in other implementations using a code like this to get the DateTime:

$date = '16/11/2020 12:00:00 a. m.';
$newDateTime = new DateTime($date);

But it throws this error:

DateTime::__construct(): Failed to parse time string (16/11/2020 12:00:00 am) at position 0 (1): Unexpected character

At first, I thought the “a. m.” part could cause it to I did this change:

$date = '16/11/2020 12:00:00 a. m.';
$date        =  str_replace('a. m.', 'am', $date);
$date        =  str_replace('p. m.', 'pm', $date);
$newDateTime = new DateTime($date);

But the error persists. My last try was this:

$date = '16/11/2020 12:00:00 a. m.';
$date        =  str_replace('a. m.', 'am', $date);
$date        =  str_replace('p. m.', 'pm', $date);
$date        =  date("Y-m-d H:s:i", strtotime($date));
$newDateTime = new DateTime($date);

But the result date I got is:

1970-01-01 00:00:00

So, what is the correct form to parse this kind of date?

Thanks.

Advertisement

Answer

You need to provide a matching format description:

<?php
$date = '16/11/2020 12:05:30 a. m.';
$date        =  str_replace('a. m.', 'am', $date);
$date        =  str_replace('p. m.', 'pm', $date);
$newDateTime = DateTime::createFromFormat('d/m/Y h:i:s A', $date);
print_r($newDateTime->format('Y-m-d h:i:s'));

The output is:

2020-11-16 12:05:30

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement