3

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.

3 Answers 3

6

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

$new_timestamp = strtotime("-7 hours", $timestamp);
Sign up to request clarification or add additional context in comments.

4 Comments

Are you sure strtotime("-07:00", 1346300336) works? I am getting back the original 1346300336.
@Justin Oh, it returns 1346357936.
I am getting the same result back 1346300336 when trying strtotime("-07:00", 1346300336)
@Justin it should be like this strtotime("-7 hours", 1346300336). You have missed the word hours
1
 $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.

2 Comments

I don't have timezones stored in the format of GMT or Pacific, I store the offset, as shown above.
Might not be ideal but you could make an array to map timezones to offsets
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.