Home > Database > Mysql Tutorial > body text

How to Achieve Timezone Synchronization Between PHP and MySQL?

Susan Sarandon
Release: 2024-11-02 09:24:02
Original
578 people have browsed it

How to Achieve Timezone Synchronization Between PHP and MySQL?

Setting Timezones for PHP and MySQL Synchronization

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.

Solutions for PHP

For PHP, ensuring timezone synchronization entails the following steps:

  • Set the default timezone:
<code class="php">define('TIMEZONE', 'Europe/Paris');
date_default_timezone_set(TIMEZONE);</code>
Copy after login
  • Use a custom timezone when calling date():
<code class="php">$finalize_at = date('Y-m-d H:i:s', strtotime('+30 minutes'));</code>
Copy after login

Solutions for MySQL

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>
Copy after login

Synchronization Verification

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!