Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

Set timezone in PHP and MySQL

I am making an application where I need to store th date in MySQL using the PHP date() function.

<?php $finalize_at = date('Y-m-d H:i:s'); ?>

These dates need to be compared in MySQL using the NOW() function to return the difference in hours, for example:

SELECT TIMESTAMPDIFF( hour, NOW(), finalize_at ) FROM plans;

But the problem is – the PHP date function date('Y-m-d H:i:s') uses the PHP timezone setting, and the NOW() function takes the MySQL timezome from the MySQL server.

I'm trying to solve doing this:

  1. date_default_timezone_set('Europe/Paris'); It works only for PHP.
  2. date.timezone= "Europe/Paris"; It works only for PHP.
  3. SELECT CONVERT_TZ(now(), 'GMT', 'MET'); This return empty.
  4. mysql> SET time_zone = 'Europe/Paris'; This throws an error from the console of MySQL.

And the timezone does not change for MySQL.

Is there any way to change the timezone for both PHP and MySQL without having to do it from the MySQL console, or set a timezone change from somewhere in php.ini and make these values available for both PHP and MySQL.

Much appreciate your support.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In PHP:

<?php
define('TIMEZONE', 'Europe/Paris');
date_default_timezone_set(TIMEZONE);

For MySQL:

<?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);

//Your DB Connection - sample
$db = new PDO('mysql:host=localhost;dbname=test', 'dbuser', 'dbpassword');
$db->exec("SET time_zone='$offset';");

The PHP and MySQL timezones are now synchronized within your application. No need to go for php.ini or MySQL console!

This is from this article on SitePoint.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...