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

时间:2013-10-21 19:18:54

标签: javascript php datetime timezone momentjs

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

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

当我致电$base->getTimestamp()时,我会按预期得到:1382360400

在我的项目中,我正在使用moment.js,当我说这个时间戳在“当地时间”时,它可以正常工作:

// 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格式返回时间戳?我希望从1382346000获得$base->getTimestamp(),这是我在做的时候得到的:

$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

1 个答案:

答案 0 :(得分:1)

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

相关问题