我有一个Unix时间戳,它被设定为+5时区,但我想将其转换为-5时区的EST标准时间。我本来想让时间戳在目标时区生成,但是我从另一个源头获取它,该源头把它放在了+5时区。
当前未修改的时间戳被转换为日期
<? echo gmdate("F j, Y, g:i a", 1369490592) ?>
$dt = new DateTime('@1369490592');
$dt->setTimeZone(new DateTimeZone('America/Chicago'));
echo $dt->format('F j, Y, g:i a');
一个更简单的方法是:
在使用gmdate()
时,将您的时区以秒为单位添加到gmdate中的unix_stamp中。
考虑我的时区是GMT+5:30。因此, 5小时30分钟转换成秒为19800
所以,我会这样做:
gmdate("F j, Y, g:i a", 1369490592+19800)
这里有一个函数可以将 Unix/GMT/UTC 时间戳转换为所需的时区,可能会对你有帮助。
function unix_to_local($timestamp, $timezone){
// Create datetime object with desired timezone
$local_timezone = new DateTimeZone($timezone);
$date_time = new DateTime('now', $local_timezone);
$offset = $date_time->format('P'); // + 05:00
// Convert offset to number of hours
$offset = explode(':', $offset);
if($offset[1] == 00){ $offset2 = ''; }
if($offset[1] == 30){ $offset2 = .5; }
if($offset[1] == 45){ $offset2 = .75; }
$hours = $offset[0].$offset2 + 0;
// Convert hours to seconds
$seconds = $hours * 3600;
// Add/Subtract number of seconds from given unix/gmt/utc timestamp
$result = floor( $timestamp + $seconds );
return $result;
}
因为John Conde的回答的编辑队列已满,所以我会添加更详细的回答。
从DateTime::__construct(string $time, DateTimeZone $timezone)
当$time参数是UNIX时间戳(例如@946684800)时,$timezone参数和当前时区被忽略...
这就是为什么在从Unix时间戳创建DateTime
对象时,你应该始终指定时区,即使是默认时区。参考John Conde的回答的代码解释:
$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');
ini_set('date.timezone', 'America/Los_Angeles'); $now = time(); $utc = new DateTime("@{$now}", new DateTimeZone('America/New_York')); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00 $utc = new DateTime("@{$now}"); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00 ini_set('date.timezone', 'UTC'); $utc = new DateTime("@{$now}", new DateTimeZone('UTC')); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00
- jmar