To store dates in MySQL using PHP's date() function and compare them using MySQL's NOW() function while factoring in timezone differences, it's crucial to align the timezones for both tools.
For PHP, ensuring timezone synchronization entails the following steps:
<code class="php">define('TIMEZONE', 'Europe/Paris'); date_default_timezone_set(TIMEZONE);</code>
<code class="php">$finalize_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));</code>
To synchronize with PHP, MySQL's timezone setting must be adjusted as well:
<code class="php">// Get current offset in minutes $now = new DateTime(); $mins = $now->getOffset() / 60; $offset = sprintf('%+d:%02d', -$mins, abs($mins)); // Update MySQL's timezone setting $db = new PDO('mysql:host=localhost;dbname=test', 'dbuser', 'dbpassword'); $db->exec("SET time_zone='$offset';");</code>
With these configurations in place, both PHP and MySQL should use the same timezone. To verify this, compare the output of date_default_timezone_get() and the result of SELECT NOW() in a MySQL query. If the timezone names match, synchronization is successful.
Remember to check the timezone settings in your application as PHP and MySQL timezones can be affected by changes in device or server settings.
The above is the detailed content of How to Achieve Timezone Synchronization Between PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!