Time difference between PHP and MySQL [duplicate]

穿精又带淫゛_ 提交于 2021-01-28 09:14:50

问题


I searched many links but so far I coudn`t find a solution to my problem.

I have a web hosting on Go Daddy, and it is returning different times for PHP and MySQL:

  • PHP Datetime =>13/02/2018 17:10:50
  • MySQL Datetime =>13/02/2018 12:10:50

I've already set my PHP timezone to:

date_default_timezone_set('America/Sao_Paulo');

Would anyone know a way to adjust the MySQL time?

Thanks


回答1:


I found my solution at this link:

https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

Actually, I synchronized my PHP and MySQL timezones. Here's the code:

define('TIMEZONE', 'America/Sao_Paulo');
date_default_timezone_set(TIMEZONE);

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

// I already have a connection function
$return = pdo_mysql("SET time_zone='$offset';");



回答2:


This is because the MySQL doesn't store timezone information on DATETIME type.

Probably your PHP script is sending a ISO8601 date string with the UTC+Timezone, so MySQL ignores the Timezone and stores only the UTC.

To avoid this, you can use the TIMESTAMP type that keeps track of the timezone.



来源:https://stackoverflow.com/questions/48774010/time-difference-between-php-and-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!