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:
<code class="php">define('TIMEZONE', 'Europe/Paris'); date_default_timezone_set(TIMEZONE);</code>
MySQL:
<code class="php">$now = new DateTime(); $mins = $now->getOffset() / 60; $sgn = ($mins < 0 ? -1 : 1); $mins = abs($mins); $hrs = floor($mins / 60); $mins -= $hrs * 60; $offset = sprintf('%+d:%02d', $hrs*$sgn, $mins); // Assuming an existing DB connection named $db $db->exec("SET time_zone='$offset';");</code>
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.
The above is the detailed content of How to Synchronize Timezones in PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!