Having Timezone problems with PHP and MySQL

前端 未结 3 1898
南方客
南方客 2020-12-09 14:37

My server time is in GMT, and I do the following whenever someone comes online.

// Set a default timezone
$defaultTimeZone = \'America/Toronto\';

// load th         


        
3条回答
  •  天涯浪人
    2020-12-09 14:57

    The trick here is to know what column type date_last_active is. I've had enough experience with TIMESTAMP and DATETIME to know that one translates (and honors) the MySQL time_zone session variable, the other doesn't.

    mysql> SET SESSION time_zone = 'America/New_York';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> create table timetest ( dt datetime NULL, ts timestamp NOT NULL DEFAULT 0 );
    Query OK, 0 rows affected (0.06 sec)
    
    mysql> INSERT INTO timetest ( dt, ts ) VALUES ( UTC_TIMESTAMP(), UTC_TIMESTAMP() );
    Query OK, 1 row affected (0.00 sec)
    
    mysql> INSERT INTO timetest ( dt, ts ) VALUES ( NOW(), NOW() );
    Query OK, 1 row affected (0.00 sec)
    
    mysql> SELECT * FROM timetest;
    +---------------------+---------------------+
    | dt                  | ts                  |
    +---------------------+---------------------+
    | 2009-06-27 17:53:51 | 2009-06-27 17:53:51 | 
    | 2009-06-27 13:53:54 | 2009-06-27 13:53:54 | 
    +---------------------+---------------------+
    2 rows in set (0.00 sec)
    
    mysql> set session time_zone='UTC';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT * FROM timetest;
    +---------------------+---------------------+
    | dt                  | ts                  |
    +---------------------+---------------------+
    | 2009-06-27 17:53:51 | 2009-06-27 21:53:51 | 
    | 2009-06-27 13:53:54 | 2009-06-27 17:53:54 | 
    +---------------------+---------------------+
    2 rows in set (0.00 sec)
    

    So, here is what I do:

    • When inserting into the database, use UTC in PHP and in MySQL. In my.cnf I have: time_zone=UTC to avoid any issues in MySQL, and in PHP I date_default_timezone_set('UTC').
    • Use UTC_TIMESTAMP() instead of NOW() - one is UTC, one uses the local (session) time zone. If you're following the first point, above, use UTC_TIMESTAMP().
    • When selecting to display to the user, set time_zone='local_time_zone' before displaying anything.
    • If you have to display stuff, then update, make sure to bracket your calls with the appropriate timezone changes in PHP and MySQL.

    Hopefully that's enough to figure out how to approach this. Let me know if you have further questions.

提交回复
热议问题