MySQL中NOW()函数返回错误时间(实际时间+4小时)求助
NOW() Returning Time 4 Hours Ahead of Actual Time Hey there, let's get to the bottom of why your SELECT NOW() AS current_time is giving you a time that's 4 hours ahead of reality. This almost always boils down to timezone misconfiguration in your MySQL server or session, so let's walk through the fixes step by step:
First, check your current MySQL timezone settings
Run this query to see what timezones your server and current session are using:SELECT @@global.time_zone, @@session.time_zone;The
@@global.time_zoneis the server-wide default, and@@session.time_zoneapplies to your current connection. If either of these is set to a timezone that's 4 hours ahead of your local time (like if you're in UTC+8 and it's set to UTC+12), that's the culprit.Temporarily fix the session timezone
If you just need to correct the time for your current session, run this command (replace'+08:00'with your actual local timezone offset):SET time_zone = '+08:00';Now run your original
SELECT NOW()query again—this should return the correct time for your session. Note that this change will reset when you disconnect.Permanently set the server timezone
To fix this for all future connections, you'll need to edit your MySQL configuration file:- On Linux systems, this is usually
/etc/my.cnfor/etc/mysql/my.cnf - On Windows, it's
my.iniin your MySQL installation directory
Add or update this line under the
[mysqld]section (use your correct timezone offset or a named timezone likeAsia/Shanghai):default-time-zone = '+08:00'Save the file and restart your MySQL server. After restarting, verify the change with the
SELECT @@global.time_zonequery.- On Linux systems, this is usually
Check client connection settings
If you're connecting to MySQL via an application (like PHP, Python, etc.), make sure your connection string specifies the correct timezone. For example, in PHP PDO, you can addtimezone=Asia/Shanghaito your DSN string to enforce the right timezone for the connection.
Once you've made these changes, re-run SELECT NOW() AS current_time—it should now return the accurate local time.
内容的提问来源于stack exchange,提问作者user4689071

