"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Synchronize Timezones in PHP and MySQL?

How to Synchronize Timezones in PHP and MySQL?

Published on 2024-11-17
Browse:225

How to Synchronize Timezones in PHP and MySQL?

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:

  • date_default_timezone_set('Europe/Paris') affects PHP only.
  • date.timezone = "Europe/Paris" remains isolated to PHP.
  • SELECT CONVERT_TZ(now(), 'GMT', 'MET') returns empty results.
  • mysql> SET time_zone = 'Europe/Paris' prompts an error in the MySQL console.

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.

Latest tutorial More>

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