Home > Database > Mysql Tutorial > How to Synchronize Timezones in PHP and MySQL?

How to Synchronize Timezones in PHP and MySQL?

Susan Sarandon
Release: 2024-11-03 11:26:02
Original
271 people have browsed it

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:

<code class="php">define('TIMEZONE', 'Europe/Paris');
date_default_timezone_set(TIMEZONE);</code>
Copy after login

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

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!

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