简体   繁体   中英

PHP MySQL query shows wrong datetime in result

I am using workbench for accessing DB connection.

My problem is when I am running the direct query in workbench the result is correct but same query I am running using PHP function the DateTime is different. MySQL server timezone: EST Linux Server timezone: EST

but the result comes in GMT timezone.

All the data entry records show EST time.

eg. Mysql Workbench result: datetime: 19:00:00 PHP query result: 22:00:00

Well , you can convert returned data to other timezone so if your time stored in EST but php showing it as GMT , you can convert it again

here is an example

// now
$date = date_create('2017-10-09 07:00:00', timezone_open('Asia/Dubai'));

function getDateByTimeZone($date,$TimeZone='US/Eastern'){
    date_timezone_set($date, timezone_open($TimeZone));
    return $date->format('Y-m-d H:i:s');
}
echo getDateByTimeZone($date);
echo "<br />";
echo getDateByTimeZone($date,'GMT');

// Output 

# 2017-10-08 23:00:00
# 2017-10-09 03:00:00

?>

assume $date is your returned data from Mysql which is in your case GMT , pass it to that function then you will get EST .

Also you can configure your PHP.init file by changing the following

date.timezone = "America/New_York"

and to make sure your php server is running under correct timezone

<?php
phpinfo();
?>

you will find Default timezone in Date Section from that information you should be able to see default timezone for your php server .

if you want to set Default timezone for single website in your server you can edit VirtualHost by adding the following

<IfModule php7_module>
php_admin_value date.timezone "America/New_York"
</IfModule>
<IfModule php5_module>
php_admin_value date.timezone "America/New_York"
</IfModule>

if you would like to set default timezone per folder you could edit htaccess file by adding the following

<IfModule !fcgid_module>
php_value date.timezone "America/New_York"
</IfModule>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM