php IntlDateFormatter 无法按预期工作

代码很简单,我想使用 IntlDateFormatter 将字符串转换为 DateTime 对象,但是结果与原始结果完全不同。我做错了什么?以下代码是基于构造DateTimeToLocalizedStringTransformer的Symfony4.3


<?php


//turn string to timestamp

$t = new \IntlDateFormatter('en_US', 2, 2, new DateTimeZone('Asia/Shanghai') , 1, 'Y-m-d H:i:s');

$t->setLenient(false);

$timestamp = $t->parse('2019-09-18 18:58:08');


//turn timestamp back to string

$date = new DateTime();

$date->setTimestamp($timestamp);

$date->setTimezone(new \DateTimeZone('Asia/Shanghai'));


echo $date->format('Y-m-d H:i:s') . "\n"; //output : 2019-01-18 18:09:00, why? 


qq_遁去的一_1
浏览 156回答 2
2回答

翻阅古今

IntlDateFormatter 的日期格式错误,您需要ICU 格式。最好使用常量而不是整数。$dateStr = '2019-09-18 18:58:08';$t = new \IntlDateFormatter('en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'Asia/Shanghai' ,IntlDateFormatter::GREGORIAN, 'yyyy-MM-dd HH:mm:ss');&nbsp;$t->setLenient(false);$timestamp = $t->parse($dateStr);//turn timestamp back to string$dateStrFromTs = date_create(null,new \DateTimeZone('Asia/Shanghai'))&nbsp; ->setTimestamp($timestamp)&nbsp; ->format('Y-m-d H:i:s');var_dump($dateStrFromTs === $dateStr);&nbsp; //bool(true)

UYOU

首先,让我们摆脱幻数和间接检查,以确保:$t = new \IntlDateFormatter(&nbsp; &nbsp; 'en_US',&nbsp; &nbsp; IntlDateFormatter::MEDIUM,&nbsp; &nbsp; IntlDateFormatter::MEDIUM,&nbsp; &nbsp; new DateTimeZone('Asia/Shanghai'),&nbsp; &nbsp; IntlDateFormatter::GREGORIAN,&nbsp; &nbsp; 'Y-m-d H:i:s');$t->setLenient(false);$timestamp = $t->parse('2019-09-18 18:58:08');var_dump(date('r', $timestamp));这打印 Fri, 18 Jan 2019 11:09:00 +0100. 那么,有什么关系呢?问题是最后一个构造函数参数。您理所当然地认为格式代码与 eg 中的相同,date()但这不是文档所说的:格式化或解析时使用的可选模式。可能的模式记录在 »&nbsp;http://userguide.icu-project.org/formatparse/datetime。Y表示“一年中的一周”。m表示一小时内的分钟。... 等等。
打开App,查看更多内容
随时随地看视频慕课网APP