$d = DateTime::createFromFormat('d-m-Y H:i:s', '2021-07-15T19:00:00.000Z');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
这不起作用并显示错误“日期字符串不正确”
我错过了什么吗?
答案 0 :(得分:1)
格式不对。 日期是使用 Z(祖鲁语)区域指示符的 UTC 日期。 格式字符 v 可用于毫秒,字符 e 可用于时区。
$d = DateTime::createFromFormat('Y-m-d\TH:i:s.ve', '2021-07-15T19:00:00.000Z');
var_dump($d);
输出:
object(DateTime)#2 (3) { ["date"]=> string(26) "2021-07-15 19:00:00.000000" ["timezone_type"]=> int(2) ["timezone "]=> 字符串(1) "Z" }
你得到的时间戳
$timeStamp = $d->getTimeStamp();
//1626375600
或使用老式函数 strtotime
$timeStamp = strtotime('2021-07-15T19:00:00.000Z');
DateTime 可识别格式“2021-07-15T19: 00: 00.000Z”。这段代码
echo date_create('2021-07-15T19:00:00.000Z')->getTimeStamp();
//1626375600
还提供正确的时间戳。
请注意:
为了正确计算时间戳,除了日期和时间之外,使用正确的时区也很重要。 如果时区不正确,则确定不正确的时间戳。 使用 DateTime::createFromFormat 的解决方案,以 \Z 的格式隐藏时区,只返回正确的日期,通常是不正确的时间戳。
答案 1 :(得分:-1)
它不起作用,因为日期 (2021-07-15T19:00:00.000Z
) 与格式 (d-m-Y H:i:s
) 不匹配。
除了格式中可见缺失的 T
、Z
和毫秒之外,它不起作用,因为格式期望日期在先,日期从年份开始。任何一年中没有任何一个月有 2021 天:-)
因为您的输入日期使用标准格式 (ISO 8601),所以类 DateTime
的构造函数能够在没有格式提示的情况下解析它。
使用:
$d = new DateTime('2021-07-15T19:00:00.000Z');
输入日期表示为相对于 UTC 时区。对于日期的计算,您不需要其他任何东西。如果要对其进行格式化(例如,将其呈现给用户),则需要使用时区。
这真的很简单,使用 $d
的 setTimeZone()
方法并传递一个 DateTimeZone
对象,如下所示:
$d = new DateTime('2021-07-15T19:00:00.000Z');
$d->setTimeZone(new DateTimeZone('Europe/Berlin'));
echo($d->format('D, d M Y H:i:s'));
它打印 Thu, 15 Jul 2021 21:00:00
(日期是在夏令时,德国在夏季是 UTC+2)。
检查它online。