How the MySQL database stores time

1. Remember not to use strings to store dates

Strings take up more space!
Date comparisons stored in strings are relatively inefficient (comparison character by character), and date-related  APIs cannot be used  for calculation and comparison.

2.  Choose between Datetime and Timestamp

Datetime 和 Timestamp 是 MySQL 提供的两种比较相似的保存时间的数据类型。
他们两者究竟该如何选择呢?

Usually we will prefer Timestamp

2.1 DateTime type has no time zone information

DateTime type has no time zone information (time zone independent)

当你的时区更换之后,比如你的服务器更换地址或者更换客户端连接时区设置的话,就会导致你从数据库中读出的时间错误。

Timestamp is related to time zone .

Timestamp 类型字段的值会随着服务器时区的变化而变化,自动换算成相应的时间,说简单点就是在不同时区,查询到同一个条记录此字段的值会不一样。

Let's demonstrate it in action!
Create table SQL statement:

CREATE TABLE `time_zone_test` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `date_time` datetime DEFAULT NULL,
  `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Insert data:

INSERT INTO time_zone_test(date_time,time_stamp) VALUES(NOW(),NOW());

View data:

select dsqlate_time,time_stamp from time_zone_test;

result:

+---------------------+---------------------+
| date_time           | time_stamp          |
+---------------------+---------------------+
| 2020-01-11 09:53:32 | 2020-01-11 09:53:32 |
+---------------------+---------------------+

Change the time zone of the current session:

set time_zone='+8:00';

View the data again:

+---------------------+---------------------+
| date_time           | time_stamp          |
+---------------------+---------------------+
| 2020-01-11 09:53:32 | 2020-01-11 17:53:32 |
+---------------------+---------------------+

Extension:  Some common sql commands about MySQL time zone settings

1. 查看当前会话时区
	SELECT @@session.time_zone;
	
2. 设置当前会话时区
	SET time_zone = 'Europe/Helsinki';
	SET time_zone = "+00:00";
	
3. 数据库全局时区设置
	SELECT @@global.time_zone;
	
4. 设置全局时区
	SET GLOBAL time_zone = '+8:00';
	SET GLOBAL time_zone = 'Europe/Helsinki';

2.2 The DateTime type consumes more space

Timestamp  only needs to use 4 bytes of storage space, but DateTime needs to consume 8 bytes of storage space. However, this also creates a problem, the time range represented by Timestamp is smaller.

DateTime :1000-01-01 00:00:00 ~ 9999-12-31 23:59:59
Timestamp: 1970-01-01 00:00:01 ~ 2037-12-31 23:59:59

Timestamp 在不同版本的 MySQL 中有细微差别。

3 Look at the MySQL date type storage space

The figure below shows the storage space occupied by the date type in MySQL 5.6:
insert image description here
It can be seen that MySQL after 5.6.4 has an extra decimal place that requires 0 to 3 bytes. Datatime and Timestamp have several different storage footprints.
For convenience, in this paper, we still default that Timestamp only needs to use 4 bytes of storage space, but DateTime needs to consume 8 bytes of storage space.

4. Is a numeric timestamp a better choice?

Many times, we also use int or bigint type values, that is, timestamps to represent time.

This storage method has some advantages of the Timestamp type, and using it for date sorting and comparison operations will be more efficient, and it is also very convenient across systems, after all, it is only a stored value. The disadvantage is also obvious, that is, the readability of the data is too poor, and you cannot see the specific time intuitively.
Timestamps are defined as follows:

The definition of timestamp is to count from a reference time, which is "1970-1-1 00:00:00 +0:00". From this time, it is represented by an integer and counted in seconds. The elapse of this time integer keeps increasing. In this way, I only need one value to perfectly represent the time, and this value is an absolute value, that is, no matter where you are in the world, the timestamp representing the time is the same, generated The values ​​are all the same, and there is no concept of time zone, so no additional conversion is required in the transmission of time in the system. Only when it is displayed to the user, it is converted to the local time in string format.

Actual operation in the database:

mysql> select UNIX_TIMESTAMP('2020-01-11 09:53:32');
+---------------------------------------+
| UNIX_TIMESTAMP('2020-01-11 09:53:32') |
+---------------------------------------+
|                            1578707612 |
+---------------------------------------+
1 row in set (0.00 sec)

mysql> select FROM_UNIXTIME(1578707612);
+---------------------------+
| FROM_UNIXTIME(1578707612) |
+---------------------------+
| 2020-01-11 09:53:32       |
+---------------------------+
1 row in set (0.01 sec)

5. Summary

Timestamp is recommended because the numerical representation of time is not intuitive enough

Each method has its own advantages, and the actual scenario is the kingly way. Let's make a simple comparison of these three methods, so that you can choose the correct storage time data type in actual development:
insert image description here

6. Set the default value of mysql date type field to support 0000 format

[mysqld]
sql-mode=STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

Guess you like

Origin blog.csdn.net/weixin_38860565/article/details/125363668