PHP Offsetting unix timestamp

2019-08-12 16:09发布

问题:

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');