我似乎无法让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()的format参数的值中未列出“v”-但据推测,我应该能够使用包含“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来添加此功能。但是,尽管他为RFC3339_EXTENDED函数创建了format常量,但他并未添加对createFromFormat的支持。如果您看看here,则不支持v选项(以毫秒为单位)。嗯是的。