0

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.

  • https://www.php.net/manual/en/datetime.createfromformat.php – aynber Apr 15 '21 at 17:08
  • Here is the relevant note from strtotime, which also applies to DateTime: `Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.` – aynber Apr 15 '21 at 17:10
  • Does this answer your question? [Convert a date format in PHP](https://stackoverflow.com/questions/2487921/convert-a-date-format-in-php) – Markus Zeller Apr 15 '21 at 17:13

1 Answers1

1

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

arkascha
  • 41,620
  • 7
  • 58
  • 90