如何计算GMT和UTC时间戳


How to calculate GMT and UTC timestamp

我一直在使用php/mysql很长一段时间,我一直使用unix_timestamp来存储日期,时间值。我已经创建了时间戳类来处理这种请求。源代码可在github上获得。

默认情况下,该类使用$_SERVER['REQUEST_TIME'],我相信它是GMT时间戳。

我的要求是根据GMT找到本地时间戳并显示给用户。换句话说,我需要使用PHP

查找任何用户的本地时间以及与GMT的秒数差异。

我如何在我的类中实现这些要求?请帮助

DateTime允许您轻松完成此操作:

// Interpret the time as UTC
$timezone = new DateTimeZone('UTC');
$datetime = new DateTime('@' . $_SERVER['REQUEST_TIME'], $timezone);
// Output as PHP's timezone
$user_timezone = new DateTimeZone(date_default_timezone_get()); // Or whatever timezone you need
$datetime->setTimeZone($user_timezone);
echo $datetime->format('Y-m-d H:i:s');

获取UTC时间戳:

date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time());