[英]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.目前,我正在请求外部 web 服务以获取一些重要信息。 However, the dates this web services return me are something like this:然而,这个 web 服务返回给我的日期是这样的:
16/11/2020 12:00:00 am 16/11/2020 12:00:00 上午
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 DateTime::__construct():无法在 position 0 (1) 解析时间字符串 (16/11/2020 12:00:00 am):意外字符
At first, I thought the "am" part could cause it to I did this change:起初,我认为“am”部分可能会导致我做了这个改变:
$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 1970-01-01 00:00:00
So, what is the correct form to parse this kind of date?那么,解析这种日期的正确形式是什么?
Thanks.谢谢。
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: output 是:
2020-11-16 12:05:30 2020-11-16 12:05:30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.