PHP Offsetting unix timestamp

可紊 提交于 2019-12-11 02:25:12

问题


I have a unix timestamp in PHP:

$timestamp = 1346300336;

Then I have an offset for timezones which I want to apply. Basically, I want to apply the offset and return a new unix timestamp. The offset follows this format, and unfortunately can't be changed due to compatibility with other code:

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

I tried:

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

But this does not work unfortunately :(. Any other ideas?

EDIT

After testing, I super surprised, but even this doesn't work:

strtotime("1346300336 -7 hours")

Returns false.

Let's approach this a bit different, what is the best way to transform the offset examples above, into seconds? Then I can simply just do $timestamp + $timezone_offset_seconds.


回答1:


You should pass the original timestamp as the second parameter to strtotime.

$new_timestamp = strtotime("-7 hours", $timestamp);



回答2:


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

I like the DateTime Class a lot.




回答3:


You can use 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');


来源:https://stackoverflow.com/questions/12190510/php-offsetting-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!