我似乎无法让DateTime::createFromFormat()
在PHP 7.0.26中工作
我的代码
date_default_timezone_set('America/New_York');
$t = '2018-02-23T11:29:16.434Z';
echo '$t: ' . json_encode($t) . PHP_EOL;
$f = DateTime::RFC3339_EXTENDED;
echo '$f: ' . json_encode($f) . PHP_EOL;
echo 'createFromFormat: ' . json_encode(DateTime::createFromFormat($f, $t)) . PHP_EOL;
echo 'getLastErrors: ' . json_encode(DateTime::getLastErrors()) . PHP_EOL;
$t = '2018-02-23T11:29:16.434+00:00';
echo '$t: ' . json_encode($t) . PHP_EOL;
echo 'createFromFormat: ' . json_encode(DateTime::createFromFormat($f, $t)) . PHP_EOL;
echo 'getLastErrors: ' . json_encode(DateTime::getLastErrors()) . PHP_EOL;
输出:
$t: "2018-02-23T11:29:16.434Z"
$f: "Y-m-d\\TH:i:s.vP"
createFromFormat: false
getLastErrors: {"warning_count":0,"warnings":[],"error_count":2,"errors":{"20":"The format separator does not match","21":"The timezone could not be found in the database"}}
$t: "2018-02-23T11:29:16.434+00:00"
createFromFormat: false
getLastErrors: {"warning_count":0,"warnings":[],"error_count":2,"errors":{"20":"The format separator does not match","21":"The timezone could not be found in the database"}}
我注意到DateTime::createFromFormat()的格式参数的值中没有列出“v” - 但据说我应该能够使用包含“v”的const DateTime::RFC3339_EXTENDED
。它还说this const was added in version 7.0
答案 0 :(得分:7)
正如CBroe所说,this是适合您的解决方案。您应该使用Y-m-d\TH:i:s.uP
而不是DateTime::RFC3339_EXTENDED
,即Y-m-d\TH:i:s.vP
:
$date = DateTime::createFromFormat("Y-m-d\TH:i:s.uP", "2018-02-23T11:29:16.434Z"); //works
我真的去看看为什么会这样,这就是我找到的。
有一个closed bug请求支持RFC3339毫秒。错误作者创建了pull request来添加此功能。但是虽然他为RFC3339_EXTENDED
函数创建了format
常量,但他没有添加对createFromFormat
的支持。如果你看一下here,就不支持v
选项(毫秒)。所以是的。
答案 1 :(得分:1)
是的,显然它仅在PHP 7.3.0中得到修复,请参见此https://3v4l.org/4nMi4