Ben
Ben

Reputation: 62384

How do you handle timezone difference calculation in PHP?

I'm being told that this below method of calculating the user's local time is sometimes not working. What's the best way to do this in PHP? What do you do?

public function getTimeOffset ($time) {
    $this->_cacheTimeOffset();  
    if ($this->timeOffsetExecuted) {
        $d = date("O");
        $neg = 1;

        if (substr($d, 0, 1) == "-") {
            $neg = -1;
            $d = substr($d, 1);
        }

        $h = substr($d, 0, 2)*3600;
        $m = substr($d, 2)*60;

        return $time + ($neg * ($h + $m) * -1) + (($this->timeOffset + $this->getDstInUse()) * 3600);
    }
    return $time;
}

Upvotes: 5

Views: 7260

Answers (4)

ajreal
ajreal

Reputation: 47321

Use the DateTime extension, such as DateTime::getOffset,
or DateTimeZone::getOffset

Some countries might have perform several timezone update,
this method DateTimeZone::getTransitions reveal the transition history

Upvotes: 2

kachar
kachar

Reputation: 2548

date('Z');

returns the UTC offset in seconds.

Upvotes: 1

Just answered a very similar question over here. I recommend you check that one out; I explained the two preferred ways of doing timezone offset calculation (using simple math, and then the datetimezone and datetime classes) pretty thoroughly.

The first way would be the easiest (and most logical) way, and that is to store their offset (if you already have it, that is) and multiply that by 3600 (1 hour in seconds), and then add that value to the current unix timestamp to get their final time of running.

Another way to do it is to use the DateTime and DateTimeZone classes. How these two classes work, as shown here, is that you create two DateTimeZone objects, one with your timezone and one with theirs; create two DateTime objects with the first parameters being "now" and the second being the reference to the DateTimeZone objects above (respectively); and then call the getOffset method on your timezone object passing their timezone object as the first parameter, ultimately getting you the offset in seconds that can be added to the current unix timestamp to get the time that their job needs to run.

Upvotes: 1

RabidFire
RabidFire

Reputation: 6330

A quick solution:

<?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>

Upvotes: -1

Related Questions