Synchronizing Timezones in PHP and MySQL
You are developing an application that requires storing dates in MySQL using the PHP date() function. Comparing these dates within MySQL using NOW() to calculate time differences is necessary. However, the PHP date() function utilizes the timezone defined in PHP, while NOW() employs the timezone configured in the MySQL server.
To resolve this issue, you have attempted various approaches:
Ultimately, the MySQL timezone remains unchanged.
Solution
Synchronize timezones in PHP and MySQL without manual console commands or modifications in php.ini:
PHP:
define('TIMEZONE', 'Europe/Paris');
date_default_timezone_set(TIMEZONE);
MySQL:
$now = new DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins d', $hrs*$sgn, $mins);
// Assuming an existing DB connection named $db
$db->exec("SET time_zone='$offset';");
This approach ensures that both PHP and MySQL utilize the same timezone, eliminating discrepancies in date storage and comparison. Additionally, it eliminates the need for manual timezone settings or modification of global configuration files.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3