Home >Backend Development >PHP Tutorial >PHP converts the GMT+8 string of the database to the user's local time zone

PHP converts the GMT+8 string of the database to the user's local time zone

WBOY
WBOYOriginal
2016-07-29 09:14:461985browse

  1. Write user time zone into cookie
  2. php reads user time zone and processes

The moment the user opens the browser, use js to get the time zone and write it into the cookie. Here you can use an open source library on github Operation

https://github.com/js-cookie/js-cookie

The specific code is as follows

        // 写入时区至Cookie,单位为分钟,但是注意,这里的Offset是负数,表示的是本地时间与GMT的差
        var d = new Date();
        Cookies.set('localZone',d.getTimezoneOffset()); 

On the PHP server side, if the time value stored in the database field is a timestamp, then It is much easier to handle, but what needs to be noted here is that if your server defaults to the timestamp of the GMT+8 time zone instead of the GMT timestamp, then you need to process it. The code is as follows (here I am using ThinkPHP Frame)

            $tmp = strtotime($strTime); //这里将Y-m-d H:i 格式的字符串转换成时间戳
            $tmp = $tmp - (8 * 3600); // 服务器储存的字符串是GMT+8的,所以,这里我减去8小时的毫秒数,也即得到GMT的时间戳
            $timeZone = -cookie('localZone'); // 因为为差,需要加上,故转成正数
            $tmp = $tmp + ($timeZone * 60); // 加上浏览器所在地方的时区
            $logInfo[$i]['access_time'] = date('Y-m-d H:i',$tmp); // 格式化时间戳为Y-m-d H:i

The above introduces how PHP converts the GMT+8 string of the database into the user's local time zone, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn