在PHP和MySQL中设置时区 [英] Set timezone in PHP and MySQL

查看:281
本文介绍了在PHP和MySQL中设置时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP date()函数存储在MySQL中的应用程序。

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

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

这些日期需要使用 NOW()函数返回小时差异,例如:

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

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

但问题是 - PHP日期函数 date('Ymd H: i:s')使用PHP时区设置, NOW()函数从MySQL服务器获取MySQL timezome。

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.

我试图解决这个问题:


  1. date_default_timezone_set '欧洲/巴黎'); 它只适用于PHP。

  2. date.timezone =Europe / Paris; 它只适用于PHP。

  3. SELECT CONVERT_TZ(now(),'GMT','MET'); 这个返回空。

  4. mysql> SET time_zone ='Europe / Paris'; 这会从MySQL控制台发出错误。

  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.

对于MySQL,时区不会改变。

And the timezone does not change for MySQL.

有没有办法更改PHP和MySQL的时区,而无需从MySQL控制台执行,或设置时区从 php.ini 的某个地方更改,这些值可用于PHP和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 from php.ini and that these values are available for both PHP and MySQL.

非常感谢您的支持。

Much appreciate your support.

推荐答案

在PHP中:

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

对于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';");

PHP和MySQL时区现在在您的应用程序中同步。不需要去 php.ini 或MySQL控制台!

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

这是从这个 SitePoint上的文章

这篇关于在PHP和MySQL中设置时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆