PHP - 获取当前 UTC 日期时间的正确方法

PHP - Correct way to get current UTC date time

我已经搜索了堆栈溢出和 google 以及其他来源来寻找答案,但是,我找到的所有答案都非常不同,出现次数最多(两次)的答案是这个:

$time = new DateTime('now', new DateTimeZone('UTC'));
echo $time->format('F j, Y H:i:s');

所以我的问题是,获取当前 UTC date/time 的 best/correct 方法是什么,如果不是,那是什么?

谢谢!

我不确定您找到的示例来自何处,但 gmdate 几乎可以肯定是从当前时间或提供的时间戳获取正确 GMT 日期和时间的最佳方式。

来自PHP docs

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

获取当前 GMT 日期时间的用法:

echo gmdate("Y/m/d H:i:s");

使用现有时间戳:

echo gmdate("Y/m/d H:i:s", $timestamp);

提供的日期值会自动从当地时区调整为 GMT。

显然,日期的格式可以通过修改第一个参数来更改为您想要的任何格式。