2013-10-21 35 views
0

我在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?我期望从$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

回答

1

时间戳没有一个时区。 DateTime对象显然内部存储时间戳,而不是日期&时间。所以当你改变它的时区时,同样的时间戳仍然存在,但你的日期&时间改变了。当你开始时,它是9个小时,改变时区后是13个小时。

+0

我想弄清楚如何“转换”时间戳。我需要一个解决方案,或至少一个解决方法。 –

+1

您可以使用'DateTimeZone :: getOffset()'计算两个时区的时区偏移量,从另一个中减去一个,并将结果添加到时间戳中。 – morgoth84

+0

谢谢! '$ base-> getTimestamp()+ $ local_tz-> getOffset($ base);'返回给我'1382346000' :-D DEMO:https://eval.in/56365 –