How do you handle timezone difference calculation

2019-01-20 11:49发布

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;
}

标签: php timezone
4条回答
beautiful°
2楼-- · 2019-01-20 12:23

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

查看更多
不美不萌又怎样
3楼-- · 2019-01-20 12:23
date('Z');

returns the UTC offset in seconds.

查看更多
We Are One
4楼-- · 2019-01-20 12:23

A quick solution:

<?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>
查看更多
放我归山
5楼-- · 2019-01-20 12:26

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.

查看更多
登录 后发表回答