How can I easily convert dates from UTC via PHP?

前端 未结 8 2343
梦谈多话
梦谈多话 2020-12-01 17:07

I am storing dates in a MySQL database in datetime fields in UTC. I\'m using PHP, and I\'ve called date_timezone_set(\'UTC\') so that all calls to date() (without timestamp)

8条回答
  •  北海茫月
    2020-12-01 17:31

    Here's what we did with our servers. We set everything to use UTC, and we display in the user's time zone by converting from UTC on the fly. The code at the bottom of this post is an example of how to get this to work; you should confirm that it works in all cases with your setup (i.e. daylight savings, etc).

    Configuring CentOS

    1. Edit /etc/sysconfig/clock and set ZONE to UTC
    2. ln -sf /usr/share/zoneinfo/UTC /etc/localtime

    Configuring MySQL

    1. Import timezones into MySQL if necessary:

      mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

    2. Edit my.cnf and add the following within the [mysqld] section:

      default-time-zone = 'UTC'

    PHP Code

    format('U');
            return ($ret < 0 ? 0 : $ret);
        }
    
        public static function UTCToPST($format, $time) {
            $dst = intval(date("I", $time));
            $tzOffset = intval(date('Z', time()));
            return date($format, $time + $tzOffset - 28800 + $dst * 3600);
        }
    
    }
    

提交回复
热议问题