我似乎无法让 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"}}
我注意到“v”未列在 DateTime::createFromFormat() 的格式参数值中-- 但据推测我应该能够使用包含“v”的 const DateTime::RFC3339_EXTENDED
。它还说 this const was added in version 7.0
最佳答案
正如 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添加此功能。但是,虽然他为 format
函数创建了一个 RFC3339_EXTENDED
常量,但他没有添加对 createFromFormat
的支持。如果你看看here ,不支持 v
选项(毫秒)。所以是的。
关于php - PHP DateTime::RFC3339_EXTENDED 损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48948657/