将 unix 格式时间从本地时间更改为 GMT


Change from Local Time to GMT for unix format time

使用

PHP/mysql,我实现了一个表单,用于使用 mktime 函数以 unix 格式在数据库中保存时间。视图窗体使用日期功能以可读格式显示时间。直到现在我才发现我使用的是本地时间,而不是按要求使用的格林威治标准时间(UTC)时间。在 sw 中更改 mktime 为 gmmktime 和 gmdate 更改日期非常容易。但问题是是否有办法将数据库中已有的时间(以 unix 格式)从本地时间转换为格林威治标准时间。谢谢

您可以使用

函数gmdate() 。看看手册。

这是我写的一个用于进行时区转换的函数。应该不言自明:

function switch_timezone($format, $time = null, 
    $to = "America/Los_Angeles", $from = "America/Los_Angeles")
{
    if ($time == null) $time = time();
    $from_tz = new DateTimeZone($from);
    $to_tz = new DateTimeZone($to);
    if (is_int($time)) $time = '@' . $time;
    $dt = date_create($time, $from_tz);
    if ($dt)
    {
        $dt->setTimezone($to_tz);
        return $dt->format($format);
    }
    return date($format, $time);
}