更改时区时,DateTime时间戳不会更改

时间:2016-10-01 00:35:41

标签: php datetime php-5.6

好吧基本上,我对PHP中DateTime的时间戳如何工作有点困惑。我希望制作两种方法,从本地时间转换为UTC,反之亦然。

我目前有这个:

/**
 * @param \IPS\DateTime $utcDateTime The UTC datetime.
 * @param \DateTimeZone $timezone The timezone to convert the UTC time to.
 * @return \IPS\DateTime New datetime object in local datetime.
 * @throws \Exception when the UTC date is not in UTC format. (debugging purposes)
 */
public static function utcToLocal($utcDateTime, $timezone)
{
    if ($utcDateTime->getTimezone()->getName() !== "UTC") {
        throw new \Exception("Date time is not UTC!");
    }
    $time = new DateTime($utcDateTime, new \DateTimeZone("UTC"));
    $time->setTimezone($timezone);
    return $time;
}

/**
 * @param \IPS\DateTime $localDateTime A datetime configured with the the user's timezone
 * @return DateTime New datetime object in UTC format
 * @throws \Exception When given datetime is already in UTC (for debugging purposes)
 */
public static function localToUtc($localDateTime)
{
    if ($localDateTime->getTimezone()->getName() === "UTC") {
        throw new \Exception("Value is already UTC");
    }

    $time = new DateTime($localDateTime, $localDateTime->getTimezone());
    $time->setTimezone(new \DateTimeZone("UTC"));
    return $time;
}

当我调试此代码时,在return $time的最后一行localToUtc(...),我的调试器会显示正确的转换: Debugger showing correct times

然而,当我评估表达式

$localDateTime->getTimestamp() === $time->getTimestamp()

它将返回true。

所以我有点困惑,我只想在更改时区时更改时间戳。我想也许我需要和getOffset()合作,但我想确保以正确的方式做到这一点。我也不想使用任何字符串格式技巧,因为我觉得这不是正确的方法。

0 个答案:

没有答案