在一台服务器上,当我运行:

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2009-05-30 16:54:29 |
+---------------------+
1 row in set (0.00 sec)

在另一台服务器上:

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2009-05-30 20:01:43 |
+---------------------+
1 row in set (0.00 sec)

当前回答

如果符合您的场景,您可以通过更改操作系统时区轻松做到这一点。

在Ubuntu系统中,使用此命令可以列出时区

sudo timedatectl list-timezones

如果需要修改操作系统的时区,需要同时执行该命令

timedatectl set-timezone America/New_York

检查操作系统时区,执行

date

然后重新启动MySQL

sudo service mysql restart

要在MySQL中检查时区,请登录并运行

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

其他回答

如果你使用PDO:

$offset="+10:00";
$db->exec("SET time_zone='".$offset."';");

如果你正在使用MySQLi:

$db->MySQLi->query("SET time_zone='".$offset."';");

关于格式化偏移量的更多信息: https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

要在MariaDB中设置标准时区,必须转到50-server.cnf文件。

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

然后您可以在mysqld部分中输入以下条目。

default-time-zone='+01:00'

例子:

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
[mysqld]

#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

### Default timezone ###
default-time-zone='+01:00'

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.

必须通过配置文件进行更改,否则MariaDB服务器重启后将重置mysql表!

要为当前会话设置它,请执行:

SET time_zone = timezonename;

在MySQL Workbench 8.0的服务器选项卡下,如果你选择状态和系统变量,你可以在这里设置它。

您可以在启动服务器时指定服务器的默认时区,请参阅http://dev.mysql.com/doc/refman/5.1/en/server-options.html,特别是——default-time-zone=timezone选项。可以查看全局时区和会话时区

SELECT @@global.time_zone, @@session.time_zone;

使用set语句设置其中一个或两个,更多细节请参见http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html。