PHP时区转换问题

标签 php unix-timestamp date-conversion timestamp-with-timezone

我有这个函数用于将请求日期转换为 GMT00 unix 时间跨度并将该时间跨度存储到数据库中。

当我尝试将 GMT00 时间跨度转换为有效的 GMT 时区(如 GMT+4:00)时,下面的函数会返回错误的时间跨度

/**
     * Convert date time from one timezone to another timezone
     *
     * @param $datetime (string): Date Time value which needs to be converted
     * @param $is_timestamp (boolean): If $datetime is a timestamp then true, otherwise false
     * @param $stimezone (string): Timezone from which to convert date and time
     * @param $dtimezone (string): Timezone in which to convert date and time
     * @param $format (string): Format in which you need date and time
     *
     * @return (misc) Converted date time string, null on failure
     */
public static function convertDateTime($datetime, $is_timestamp = false, $stimezone = "GMT+00:00", $dtimezone = "GMT+00:00", $format = null) {
    if ($is_timestamp) {
        $datetime = date("Y-m-d H:i:s", $datetime);

    } else {
        $datetime = date("Y-m-d H:i:s", strtotime($datetime));
    }

    try {
        $date = new \DateTime($datetime, new \DateTimeZone($stimezone));
        $date->setTimezone(new \DateTimeZone($dtimezone));

        if (!empty($format)) {
            //return $date->format($format);
            return gmdate($format, $date->getTimestamp());

        } else {
            return $date->getTimestamp();
        }

    } catch (\Exception $e) {
        return null;
    }
}

最佳答案

这里的问题是那一行:return gmdate($format, $date->getTimestamp());

时间戳不带时区。unix 时间戳是自 1970 年 1 月 1 日午夜以来花费的秒数,UTC。 无论时区如何,都是一样的。因此,当您使用 $date->getTimestamp() 时,您会“丢失”$date< 的时区元数据 对象。

所以你可以通过修改来修复你的代码

return gmdate($format, $date->getTimestamp());

通过

return $date->format($format);

希望对您有所帮助。

关于PHP时区转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361242/

相关文章:

sql-server - 处理 varchar 日期转换中超出范围的值

javascript - 以 mm/dd/yyyy 格式验证日期的正则表达式

php - 观察 root 并检查 PHP 中的新文件

python - django - 使 datetimefield 接受 unix 时间戳

c++ - 将一个字符串转换为另一个字符串的问题

db2 - 将 db2 日期戳转换为 Unix 时间戳

linux - Linux下如何查看文件创建时间?

php - MongoDB 为帖子存储 "like"的最佳技术

php - 处理超大阵列的最佳实践? D B?

php - 在自定义 Magento 管理模块中,如何在页面之间传递数据?