douke1942 2016-10-01 00:35
浏览 50

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

Alright so basically, I am a little confused about how the timestamp works in DateTime in PHP. I wish to make two methods that convert from a local time to UTC and vice versa.

I currently have this:

/**
 * @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;
}

When I debug this code, at the last line return $time in localToUtc(...) my debugger shows the correct conversions: Debugger showing correct times

However, when I evaluate the expression

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

it will return true.

So I am a little confused, I just want the timestamps to change when I change the timezone. I am thinking maybe I need to work with getOffset() but I want to make sure I do it in the correct way. I'd also prefer not to use any string format tricks because I feel like that is not the correct way.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
    • ¥15 opencv 无法读取视频
    • ¥15 用matlab 实现通信仿真
    • ¥15 按键修改电子时钟,C51单片机
    • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
    • ¥20 5037端口被adb自己占了
    • ¥15 python:excel数据写入多个对应word文档
    • ¥60 全一数分解素因子和素数循环节位数
    • ¥15 ffmpeg如何安装到虚拟环境
    • ¥188 寻找能做王者评分提取的