2013-05-25 221 views
10

我有一个设置为+5 Unix时间戳,但我想将其转换为-5,EST标准时间。我只是想让时间戳在那个时区生成,但是我从另一个来源加上了+5。将Unix时间戳转换为时区?

当前未修改的时间戳被转换成日期

<? echo gmdate("F j, Y, g:i a", 1369490592) ?> 

回答

30

使用DateTimeDateTimeZone

$dt = new DateTime('@1369490592'); 
$dt->setTimeZone(new DateTimeZone('America/Chicago')); 
echo $dt->format('F j, Y, g:i a'); 

See it in action

+3

曾任职完美。谢谢=) –

+0

纠正我,如果我错了@约翰当然这不起作用?此方法将使用创建DateTime对象实例时未指定的系统(PHP配置)默认时区。像[这里](http://stackoverflow.com/a/17098897/234631)。所以当转换到美国/芝加哥时,它会改变系统时区,假设它不像+ UNIX时间戳本身那样与+5不一样,他试图改变10个区域? –

+1

@Stefan这确实是错误的。 Unix时间戳总是UTC。一些有趣的代码示例: 函数ini_set( 'date.timezone', '美洲/洛杉矶'); $ now = time(); $ UTC =新日期时间( “@ {$现在}”,新DateTimeZone( '美国/纽约')); echo“{$ utc-> format('c')} \ n”; // 2014-08-27T15:24:09 + 00:00 $ UTC =新日期时间( “@ {$现在}”); echo“{$ utc-> format('c')} \ n”; // 2014-08-27T15:24:09 + 00:00 ini_set('date.timezone','UTC'); $ UTC =新日期时间( “@ {$现在}”,新DateTimeZone( 'UTC')); echo“{$ utc-> format('c')} \ n”; // 2014-08-27T15:24:09 + 00:00 –

0

至于因为编辑队列John Conde's answer充满我会添加更详细回答。

DateTime::__construct(string $time, DateTimeZone $timezone)

在$时区参数和当前时区被忽略当 $时间参数要么是一个UNIX时间戳(如@ 946684800)...

这是当从unix时间戳创建DateTime对象时,您应始终指定时区,甚至默认值的主要原因。在使用gmdate(),添加时区,以秒gmdate到unix_stamp

:请解释由John Conde's answer启发代码:

$dt = new DateTime('@1369490592'); 

// use your default timezone to work correctly with unix timestamps 
// and in line with other parts of your application 
date_default_timezone_set ('America/Chicago'); // somewhere on bootstrapping time 
… 
$dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); 

// set timezone to convert time to the other timezone 
$dt->setTimeZone(new DateTimeZone('America/Chicago')); 

echo $dt->format('F j, Y, g:i a'); 
0

容易方式做到这一点是。

考虑我的时区是GMT + 5:30。所以在几秒钟内5小时30分钟

于是,我就这样做:

gmdate("F j, Y, g:i a", 1369490592+19800)