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

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

问题描述

我正在制作一个应用程序,我需要使用 PHP date() 函数在 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'); ?>

这些日期需要在 MySQL 中使用 NOW() 函数进行比较,以返回小时的差异,例如:

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;

但问题是 – PHP 日期函数 date('Ymd H:i:s') 使用 PHP 时区设置,而 NOW() 函数采用来自 MySQL 服务器的 MySQL 时区.

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'); 仅适用于 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 in php.ini and make these values available for both PHP and MySQL.

非常感谢您的支持.

推荐答案

在 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天全站免登陆