PHP偏移Unix时间戳

3

我有一个PHP中的Unix时间戳:

$timestamp = 1346300336;

然后我有一个时区偏移量需要应用。基本上,我想应用这个偏移量并返回一个新的Unix时间戳。该偏移量遵循以下格式,不幸的是由于与其他代码的兼容性问题不能更改:

$offset_example_1 = "-07:00";
$offset_example_2 = "+00:00";
$offset_example_3 = "+07:00";

我尝试过:

$new_timestamp = strtotime($timestamp . " " . $offset_example_1);

但是不幸的是,这并不能起作用 :(. 有其他的想法吗?

编辑

经过测试,我非常惊讶,但即使这样也不起作用:

strtotime("1346300336 -7 hours")

返回 false。
让我们换个方式看待这个问题,如何将上面的偏移示例转换为秒?然后我就可以简单地执行 $timestamp + $timezone_offset_seconds
3个回答

6
你应该将原始时间戳作为第二个参数传递给 strtotime
$new_timestamp = strtotime("-7 hours", $timestamp);

你确定 strtotime("-07:00", 1346300336) 能正常工作吗?我得到的结果是原始时间戳 1346300336 - Justin
@Justin Oh,它返回“1346357936”。 - xdazz
当我尝试使用 strtotime("-07:00", 1346300336) 时,我得到了相同的结果 1346300336 - Justin
@Justin 应该是这样的 strtotime("-7 hours", 1346300336)。你漏掉了 hours 这个单词。 - Maduka Jayalath

1
 $dt = new DateTime();
 $dt->setTimezone('GMT'); //Or whatever
 $dt->setTimestamp($timestamp);
 $dt->setTimezone('Pacific');
 //Echo out/do whatever
 $dt->setTimezone('GMT');

我非常喜欢DateTime类。


我没有以“GMT”或“Pacific”格式存储时区,而是存储偏移量,如上所示。 - Justin
可能不是最理想的方法,但你可以创建一个数组来将时区映射到偏移量。 - DaOgre

1
您可以使用DateInterval:
$t = 1346300336;
$date = DateTime::createFromFormat('Y-m-d', date('Y-m-d', $t));
$interval = DateInterval::createFromDateString('-7 hours'); 
$date->add($interval);

echo $date->getTimestamp();
echo $date->format('Y-m-d H:i:s');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接