Многие интернет-ресурсы написаны таким образом, что для корректной их работы требуется установка верной даты и времени (часового пояса) MySQL — а также указания часового пояса в настройках РНР. Часовой пояс является одной из настроек сервера баз данных и может задаваться локально, глобально или для текущей пользовательской сессии.
Чтобы определить время MySQL нужно редактировать конфигурационный файл (для большинства дистрибутивов он располагается по адресу /etc/mysql/my.cnf) или задавать переменные непосредственно в консоли сервера баз данных. Рассмотрим задание временной зоны при помощи переменных.
Авторизуемся в консоли MySQL (потребуется пароль пользователя root)
mysql -u root -p
При помощи запроса SELECT NOW(); можно просмотреть текущие дату и время MySQL
mysql> SELECT NOW();
+———————+
| NOW() |
+———————+
| 2017-08-31 21:21:56 |
+———————+
1 row in set (0.00 sec)
Можно вывести только время без даты. Для этого нужно выполнить запрос SELECT CURTIME();
mysql> SELECT CURTIME();
+————+
| CURTIME() |
+————+
| 21:24:16 |
+————+
1 row in set (0.00 sec)
Установить часовой пояс для определенного пользователя можно выполнив в консоли MySQL
SET time_zone = ‘+05:00’;
Чтобы изменения сохранились после перезагрузки и имели силу для всего сервера баз данных нужно задать глобальную переменную:
SET GLOBAL time_zone = ‘+5:00’;
Можно также указывать имя временной зоны — например, MSK для Москвы, но лучшей практикой является задавать часовой пояс определяя разницу с временем по Гринвичу как сделано выше
Также время опционально для конкретной сессии
mysql> set @@session.time_zone = ‘+00:00’;
Можно выяснить требуется ли задавать время для сессии выполнив:
mysql> SELECT @@global.time_zone, @@session.time_zone;
+———————+———————+
| @@global.time_zone | @@session.time_zone |
+———————+———————+
| SYSTEM | SYSTEM |
+———————+———————+
1 row in set (0.00 sec)
В данном случае время сессии совпадает с системным и непосредственное его задание не требуется.
Время в MySQL может указываться в TIMESTAMP и DATETIME
- DATETIME (значение занимает 8 байт) — время не зависит от временной зоны и выводится в том виде, в котором было задано. Изменив время в MySQL изменить значение в DATETIME нельзя (может меняться при установке времени для сессии). Выводится в виде YYYY-MM-DD-HH-MM-SS
- TIMESTAMP (значение занимает 4 байта) является абсолютным значением времени с начала эпохи Unix — с полуночи 1 января 1970 года, при выводе из базы учитывается часовой пояс (указанный для системы, MySQL в целом или сессии MySQL), именно значение в TIMESTAMP обычно приходится корректировать. Значение TIMESTAMP выводится запросом SELECT NOW(); — TIMESTAMP же корректируется всеми приведенными в данном материале командами.
Общее правило для корректной работы приложения — время РНР должно совпадать с временем MySQL. Если корректируется время в РНР, то скорректировать его нужно и в MySQL.
Чаще всего на практике для сервера на котором работают один или несколько сайтов ценной оказывается команда:
SET GLOBAL time_zone = ‘+5:00’;
Кроме часового пояса MySQL приходится задавать часовой пояс в настройках РНР и системное время на сервере.
My server is running in MDT
So I used following one to convert EST
SET time_zone = '-5:00'
But, how can I switch it to EDT
because
While `EST` is only valid in winter, while in summer how to change it to `EDT`
I just try to used named time zone. But I am getting following error
#1298 - Unknown or incorrect time zone: 'America/Toronto'
I don’t understand how to solve this problem
How can i switch
UTC -05 TO UTC-04
asked Apr 1, 2011 at 6:52
GowriGowri
16.4k25 gold badges99 silver badges160 bronze badges
0
For Linux, BSD, and Mac OS X if you need to load the timezone table do this:
$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -uroot mysql
answered Jun 5, 2013 at 17:21
Steve TauberSteve Tauber
9,2015 gold badges41 silver badges46 bronze badges
3
Since you’re using Windows, your going to have to import the time zone description tables to your MySQL server.
http://dev.mysql.com/downloads/timezones.html
Mike
22.9k14 gold badges74 silver badges87 bronze badges
answered Jun 8, 2011 at 18:58
Alpha01Alpha01
8101 gold badge7 silver badges16 bronze badges
2
For me on Windows using WampServer:
- download the POSIX version from https://dev.mysql.com/downloads/timezones.html
- unzip it
- put all files in wamp mysql data: C:wampbinmysqlmysql5.7.11datamysql
- restart wamp
More Info:
“To use a time zone package that contains .frm, .MYD, and .MYI files for the MyISAM time zone tables, download and unpack it. These table files are part of the mysql database, so you should place the files in the mysqlsubdirectory of your MySQL server’s data directory. Stop the server before doing this and restart it afterward”
http://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html#time-zone-installation
answered Sep 28, 2016 at 14:13
AndrewAndrew
17.8k12 gold badges102 silver badges112 bronze badges
In case of Mysql8 and want to set EDT timezone ‘America/New_York’ then follow the below steps:
- Go to the /etc/my.cnf
- Add this under [mysqld]
default-time-zone=’America/New_York’ - systemctl restart mysqld
If you face the issue realted fatal error like this:
Fatal error: Illegal or unknown default time zone
Then do the following steps:
-
first remove the entry from /etc/my.cnf file for default-time-zone=’America/New_York’
-
Go to shell(exit from mysql) and run the command
$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
-
Add the line again
-
Restart mysql
answered Aug 7, 2020 at 13:19
AtulAtul
2,85824 silver badges38 bronze badges
2
Have you tried using a zoneinfo name such as «America/New_York» instead of the abbreviation (which is only valid for half the time)?
Ideally, you shouldn’t use the server time zone at all of course — store dates in UTC and then convert it to the appropriate time zone in the client code. (This does depend on what you’re storing, mind you. Future date/time values specified by a user with a time zone should be stored that way, not converted to any other time zone, in case the rules change between now and the future date/time. But for instants in time recorded by machines, e.g. for logging, transactions etc, I’d definitely store UTC. I would never suggest storing «just the local time and assume that the server and the client have the same rules».)
answered Apr 1, 2011 at 6:59
Jon SkeetJon Skeet
1.4m851 gold badges9046 silver badges9133 bronze badges
11
Just for the sake of completeness, Mac users can find mysql_tzinfo_to_sql
utility in /usr/local/mysql/bin
directory.
Hence the complete command will be /usr/local/mysql/bin/mysql_tzinfo_to_sql /usr/share/zoneinfo | ./mysql -p -u root mysql
I spent hours to find the utility, the above path may save yours!
answered Jun 7, 2019 at 19:15
Nadeem JamaliNadeem Jamali
1,3333 gold badges16 silver badges26 bronze badges
My server is running in MDT
So I used following one to convert EST
SET time_zone = '-5:00'
But, how can I switch it to EDT
because
While `EST` is only valid in winter, while in summer how to change it to `EDT`
I just try to used named time zone. But I am getting following error
#1298 - Unknown or incorrect time zone: 'America/Toronto'
I don’t understand how to solve this problem
How can i switch
UTC -05 TO UTC-04
asked Apr 1, 2011 at 6:52
GowriGowri
16.4k25 gold badges99 silver badges160 bronze badges
0
For Linux, BSD, and Mac OS X if you need to load the timezone table do this:
$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -uroot mysql
answered Jun 5, 2013 at 17:21
Steve TauberSteve Tauber
9,2015 gold badges41 silver badges46 bronze badges
3
Since you’re using Windows, your going to have to import the time zone description tables to your MySQL server.
http://dev.mysql.com/downloads/timezones.html
Mike
22.9k14 gold badges74 silver badges87 bronze badges
answered Jun 8, 2011 at 18:58
Alpha01Alpha01
8101 gold badge7 silver badges16 bronze badges
2
For me on Windows using WampServer:
- download the POSIX version from https://dev.mysql.com/downloads/timezones.html
- unzip it
- put all files in wamp mysql data: C:wampbinmysqlmysql5.7.11datamysql
- restart wamp
More Info:
“To use a time zone package that contains .frm, .MYD, and .MYI files for the MyISAM time zone tables, download and unpack it. These table files are part of the mysql database, so you should place the files in the mysqlsubdirectory of your MySQL server’s data directory. Stop the server before doing this and restart it afterward”
http://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html#time-zone-installation
answered Sep 28, 2016 at 14:13
AndrewAndrew
17.8k12 gold badges102 silver badges112 bronze badges
In case of Mysql8 and want to set EDT timezone ‘America/New_York’ then follow the below steps:
- Go to the /etc/my.cnf
- Add this under [mysqld]
default-time-zone=’America/New_York’ - systemctl restart mysqld
If you face the issue realted fatal error like this:
Fatal error: Illegal or unknown default time zone
Then do the following steps:
-
first remove the entry from /etc/my.cnf file for default-time-zone=’America/New_York’
-
Go to shell(exit from mysql) and run the command
$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
-
Add the line again
-
Restart mysql
answered Aug 7, 2020 at 13:19
AtulAtul
2,85824 silver badges38 bronze badges
2
Have you tried using a zoneinfo name such as «America/New_York» instead of the abbreviation (which is only valid for half the time)?
Ideally, you shouldn’t use the server time zone at all of course — store dates in UTC and then convert it to the appropriate time zone in the client code. (This does depend on what you’re storing, mind you. Future date/time values specified by a user with a time zone should be stored that way, not converted to any other time zone, in case the rules change between now and the future date/time. But for instants in time recorded by machines, e.g. for logging, transactions etc, I’d definitely store UTC. I would never suggest storing «just the local time and assume that the server and the client have the same rules».)
answered Apr 1, 2011 at 6:59
Jon SkeetJon Skeet
1.4m851 gold badges9046 silver badges9133 bronze badges
11
Just for the sake of completeness, Mac users can find mysql_tzinfo_to_sql
utility in /usr/local/mysql/bin
directory.
Hence the complete command will be /usr/local/mysql/bin/mysql_tzinfo_to_sql /usr/share/zoneinfo | ./mysql -p -u root mysql
I spent hours to find the utility, the above path may save yours!
answered Jun 7, 2019 at 19:15
Nadeem JamaliNadeem Jamali
1,3333 gold badges16 silver badges26 bronze badges
How do I set the time zone of MySQL?
Your local time zone may differ from your server’s MySQL time zone. That makes interpreting data in your database very difficult. Ideally, MySQL time zone should be the same as your own to handle data more efficiently.
This guide will help you change the time zone on your MySQL server, making it easier and more intuitive to read server logs and other data.
Prerequisites
- A user account with root or sudo privileges
- A Linux server running MySQL
- A root user account for the MySQL database
- A terminal window / command line (Ctrl-Alt-T, Search > Terminal)
- An SSH connection to your server (if working remotely)
Find Current MySQL Time Zone
Open a terminal window. If you’re working remotely, connect to your server over SSH, using root.
Enter the following to check the current global time zone in MySQL:
sudo mysql –e “SELECT @@global.time_zone;”
By default, the system will display a value of SYSTEM for your time zone. This indicates that the time zone in MySQL is synchronized with the server’s time zone.
To display a timestamp from the server, enter the following:
date
The system should display the date, time, and time zone of the server. For example,
Tue Jan 21 11:33:35 MST 2020
The time zone is indicated by the letter code. In this case, it’s set to Mountain Standard Time (MST).
Display a timestamp from the MySQL server:
sudo mysql –e “SELECT NOW();”
The system should display the current time in MySQL.
Changing the Time Zone in MySQL
Option 1: Use the SET GLOBAL time_zone Command
Use this option to set a new GMT value for the server’s global MySQL time zone:
sudo mysql -e "SET GLOBAL time_zone = ‘-6:00’;"
Instead of -6:00
, enter the GMT value you desire. If executed correctly, there is no response output.
Check the new value of your server’s MySQL time zone setting:
sudo mysql -e "SELECT @@global.time_zone;"
Once you change the time zone, previously stored datetime and timestamps are not updated.
Note: The sudo mysql -e "SET GLOBAL time_zone = 'timezone';"
command modifies the global time zone in MySQL for the duration of the current service uptime. Once the MySQL service is restarted, the settings return to the default (SYSTEM).
For that reason, a much better option is setting the time zone by editing the MySQL configuration file.
Option 2: Edit the MySQL Configuration File
MySQL settings can be changed by editing the main my.cnf configuration file. Open the file for editing:
sudo nano /etc/mysql/my.cnf
Scroll down to the [mysqld]
section, and find the default-time-zone = "+00:00"
line. Change the +00:00
value to the GMT value for the time zone you want. Save the file and exit.
In the example below we set the MySQL Server time zone to +08:00
(GMT +8).
Note: If you are working with a fresh MySQL install, your /etc/mysql/my.cnf file might not have any settings in it. If that is the case, scroll down to the bottom of the document and add the following:
[mysqld] default-time-zone = "+00:00"
Instead of +00:00
type the time zone you want to configure.
Restart the MySQL server to apply changes:
sudo service mysql restart
Check the time zone and current time again:
sudo mysql –e “SELECT @@global.time_zone;”
sudo mysql –e “SELECT NOW();”
Conclusion
In this article, you have learned two different methods for changing the default time zone in MySQL.
If you also need to set the time zone on your Ubuntu server, refer to How to Set or Change Timezone on Ubuntu.
- Display the Current Time in the Server in MySQL
- Change Configuration File to Change the Time Zone in MySQL
- Change
Global time_zone
Variable to Change the Time Zone in MySQL - Change Time Zone Only For Session in MySQL
There are a lot of articles written about MySQL and time zone management, but in this article, we will try to fill in the missing information. We will go through how to efficiently deal with the time zones.
Display the Current Time in the Server in MySQL
Sometimes, when working with a MySQL server, you need to deal with different time zones, which can sometimes confuse you. For example, you need to set MySQL Server time according to the customer’s time or migrate data to different servers and time zones.
When you switch to a Daylight Saving Time (DST) time zone, it can also happen. To ensure that the time zone is the same as planned, you must check or change the MySQL server time zone.
First of all, we need to check the current time in the MySQL server to check if it is the desired time zone.
SELECT NOW();
+---------------------+
| NOW() |
+---------------------+
| 2022-02-19 21:58:15 |
+---------------------+
1 row in set (0.00 sec)
We can also query the current global and session time zone values.
SELECT @@GLOBAL.time_zone, @@SESSION.time_zone;
The default response is system
, which means the server and system time zones are the same.
+--------------------+--------------------+
| @@GLOBAL.time_zone |@@SESSION.time_zone |
+--------------------+--------------------+
| SYSTEM | SYSTEM |
+--------------------+--------------------+
1 row in set (0.00 sec)
There are several ways to change the time zone; let’s see each one by one.
Change Configuration File to Change the Time Zone in MySQL
The easiest method is to edit the configuration file and set the default time zone. You can open the my.cnf
configuration file from the terminal from the Linux server by the following code.
$ sudo vi /etc/mysql/my.cnf
After opening the file, we need to scroll down a bit to find the [mysqld]
section, and here we will see default-time-zone = "+00:00"
. Here "+00:00"
shows an offset from the GMT zone.
We can change it to Hungary’s time zone by setting "+01:00"
. In some cases, it can happen that you will not have the [mysqld]
section; in that case, you need to add it to the end of the file.
After editing the file, we need to close it and restart the server using the following command.
$ sudo service mysql restart
Change Global time_zone
Variable to Change the Time Zone in MySQL
We can also change the server’s global time zone and set a new GMT offset value.
SET GLOBAL time_zone = '-4:00';
In this command, you need to set the GMT offset of your time zone. We set it to GMT -4:00
hrs.
You can also use other definitions, like changing variables or writing specific time zone names.
SET GLOBAL time_zone = 'Europe/Budapest';
SET @@global.time_zone = '+02:00';
We can have a small issue if we use specific time zones’ names instead of numerical values. If we get an Unknown or incorrect time zone
error, time zone data is not loaded in the MySQL server.
You can solve this issue by following Populating the Time Zone Tables.
Change Time Zone Only For Session in MySQL
As you see, we have queried two variables initially; one of them is system_time_zone
.
By changing this variable, you will not change the global time zone but just the time zone per session; after restarting the server and running again, you will get back to the original time zone.
SET time_zone = "+00:00";