Storing datetime as UTC in PHP/MySQL

前端 未结 6 1634
悲哀的现实
悲哀的现实 2020-11-30 22:08

Everywhere I read about converting time to a user\'s timezone says that the best method is to store a date and time in UTC then just add the user\'s timezone offset to this

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 22:40

    As @Haluk suggests, you can store the date as a UTC datetime . I'm complementing his answer for situations when the date you want to insert comes from PHP code, and adding some details about how it works :

    $pdo = new PDO('mysql:host=mydbname.mysql.db;dbname=mydbname', 'myusername', 'mypassword');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $insertStmt = $pdo->prepare("insert into test (last_modified)"
        ." values(:last_modified)");
    $insertStmt->bindParam(':last_modified', $lastModified, PDO::PARAM_STR);
    $lastModified = gmdate("Y-m-d H:i:s");
    $insertStmt->execute();
    

    Actually datetime in PHP doesn't have a timezone associated to it. What is passed to PDO is just a string, in one of the formats recognized by MySQL, representing the date in UTC timezone. For example if the date is 2015-10-21 19:32:33 UTC+2:00, the code above just tells MySQL to insert 2015-10-21 17:32:33. gmtdate("Y-m-d H:i:s") gives you the current date in such a format. In any case, all you need to do is build the string representing the date you want to insert in UTC time.

    Then, when you read the date, you have to tell PHP that the timezone of the date you just retrieved is UTC. Use the code in Haluk's answer for this.

提交回复
热议问题