首页 > 解决方案 > PHP IntlDateFormatter 在不同的服务器上返回不同的值

问题描述

IntlDateFormatter在这些不同的服务器上返回不同的 UTC 时间值的原因是什么(请参阅下面示例中的最后一个输出行)?

服务器 A

> php --version
PHP 7.3.6 (cli) (built: Jun 17 2019 21:27:20) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies

> php -a
Interactive shell

php > $fmt = new \IntlDateFormatter('en_US', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN);
php > echo $fmt->format(new \DateTime('July 1, 2019 12:00pm'));
Monday, July 1, 2019 at 12:00:00 PM GMT

服务器 B

> php --version
PHP 7.3.7 (cli) (built: Jul  3 2019 22:04:27) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.7, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.7, Copyright (c) 1999-2018, by Zend Technologies

> php -a
Interactive shell

php > $fmt = new \IntlDateFormatter('en_US', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN);
php > echo $fmt->format(new \DateTime('July 1, 2019 12:00pm'));
Monday, July 1, 2019 at 12:00:00 PM Coordinated Universal Time

标签: phpintl

解决方案


服务器对 DateTime 的默认时区有不同的默认设置。您必须为 DateTime 设置相同的时区才能获得相同的输出。仅为 IntlDateFormatter 设置时区是不够的。

<?php
$fmt = new \IntlDateFormatter(
  'en_US', 
  \IntlDateFormatter::FULL, 
  \IntlDateFormatter::FULL, 
  'UTC', 
  \IntlDateFormatter::GREGORIAN
);
echo $fmt->format(new \DateTime('July 1, 2019 12:00pm', new \DateTimeZone('UTC')));

推荐阅读