转换时区会产生相同的时间戳

Converting time zones yields same timestamp

本文关键字:时间戳 时区 转换      更新时间:2023-09-26

我在PHP中有一个DateTime对象。 在这里:

$base = new DateTime('2013-10-21 09:00', new DateTimeZone('America/New_York'));

当我打电话给$base->getTimestamp()时,正如预期的那样,我得到:1382360400

在我的项目中,我正在使用 moment.js,当我告诉 moment 这个时间戳是"本地时间"时,它工作正常:

// Correct :)
moment.unix(1382360400).local().format('LLLL') // Monday, October 21 2013 9:00 AM

问题是,我的应用程序中的所有其他日期都是UTC格式(除了这个),所以在我的JavaScript代码中,我有这个:

var theDate =  moment.unix(timestamp).utc();

对于所有其他日期,这有效,但不适用于此日期。 1382360400是"本地时间",而不是 UTC。 我想打电话给setTimezone可以解决这个问题,所以我做了$base->setTimezone(new DateTimeZone('UTC'));.

打电话给我var_dump($base)

object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2013-10-21 13:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

这看起来是正确的,但是当我做$base->getTimestamp()时,我又1382360400了! 不对! 我显然没有得到正确的日期。

// Incorrect :(
moment.unix(1382360400).utc().format('LLLL')  // Monday, October 21 2013 1:00 PM

如何让 PHP 的DateTime以 UTC 格式返回时间戳? 我希望从$base->getTimestamp()那里得到1382346000,这就是我这样做时得到的:

$UTC = new DateTime('2013-10-21 09:00', new DateTimeZone('UTC'));
echo $UTC->getTimestamp();

那么,如何将我的DateTime对象转换为 UTC 并获得我想要的时间戳?

// Correct :)
moment.unix(1382346000).utc().format('LLLL')  // Monday, October 21 2013 9:00 AM

(PHP 演示:https://eval.in/56348)

时间戳没有时区。DateTime对象显然在内部存储时间戳,而不是日期和时间。因此,当您更改时区时,相同的时间戳仍然存在,但您的日期和时间发生了变化。开始时是 9 小时,更改时区后是 13 小时。