简体   繁体   中英

PHP datetime returned from mysql is wrong

I am getting this weird behavior when fetching a datetime column from mysql table.

Here is the scenario:

There's a datetime column in notifications table where the date and time stored is correct.

But when I query the db from php, I get the wrong time (UTC + 0:00 which is supposed to UTC - 05:00) My system timezone is UTC - 05:00.

Even PHP's date function returns the correct date and time.

I have attached 3 images below showing time from the server, MySQL and PHP (with the issue)

I changed the system timezone, mysql timezone and php timezone but still the issue persists.

The server is nginx with php 7.0 on an ubuntu machine.

Please help me fix the issue. MySQL通知表 服务器时间 PHP日期问题

Timezones are one of the most annoying things you can deal with in a system. As a rule of thumb, I ALWAYS make sure all servers/containers/configs/etc... are all set to UTC and save UTC into the database. If you need to display something else, you can store the account/user timezone in the database and transform it before displaying the information.

It is amazing how many projects I have come into that use PST/PDT as a timezone and it causes HUGE issues down the line.

Also, I would recommend using Carbon as a helper lib for DateTime object in PHP. https://github.com/briannesbitt/Carbon

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