【发布时间】:2025-12-10 09:45:01
【问题描述】:
我在 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)
【问题讨论】:
标签: javascript php datetime timezone momentjs