Cliché! How database storage time? Do you really know?

We usually inevitable development time is to be stored, for example, we want to record time operating table this record, recording the transaction transfers time, departure time record and so on. You will find this time with us to develop this thing is still very closely linked with the good and bad business even give us a great deal of influence function. So, we need a fresh start, get to know about this thing.

This is a short and pithy article, read will be able to learn a lot!

1. Remember not to use strings to store dates

I remember when I was in college so done, and now a lot of newcomers do not understand the database will be so dry, we can see the advantages of this way of storing the date is still there, is straightforward, easy to use.

But this is not the right way, there will be the following two main issues:

  1. A larger space occupied by a string!
  2. Date comparison character string storage efficiency is relatively low (for comparison character by character), not associated with the date evaluated and compared to API.

Choice between 2.Datetime and Timestamp

Datetime and Timestamp are two types of data provided by MySQL relatively similar save time. They both how should choose?

Usually we will be the preferred Timestamp. I said the following about how to do this!

2.1 DateTime types do not have time zone information

DateTime type is no time zone information (irrespective of time zone) , the time zone is stored in the current session type DateTime time corresponding to the set time. So there will be the problem? When you replace the time zone, such as your address or server replacement replacement zone setting client connections, it would lead you read from the database the wrong time. Do not underestimate this problem, many systems because of this issue sudden, a lot of jokes.

Timestamp and time zone related . Timestamp Value field type will vary with the time zone of the server, automatically converted into the corresponding time, he said the simple point is in a different time zone, the same query to a record value of this field will be different.

The following practical demonstration of what!

Built 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 date_time,time_stamp from time_zone_test;复制代码

result:

+---------------------+---------------------+
| date_time           | time_stamp          |
+---------------------+---------------------+
| 2020-01-11 09:53:32 | 2020-01-11 09:53:32 |
+---------------------+---------------------+复制代码

Now we run

Change the time zone for 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 |
+---------------------+---------------------+复制代码

Extended: Some sql command on a common time zone setting of MySQL

# 查看当前会话时区
SELECT @@session.time_zone;
# 设置当前会话时区
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
# 数据库全局时区设置
SELECT @@global.time_zone;
# 设置全局时区
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';复制代码

Larger 2.2 DateTime type space-consuming

Timestamp only uses 4 bytes of storage space, but DateTime takes 8 bytes of storage space. However, this is also causing a problem, Timestamp represents the time range 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 there are nuances in the different versions of MySQL.

3 Look at MySQL date types of storage space

The figure is the share of MySQL version 5.6 Date Type Storage:

It can be seen after MySQL 5.6.4 requires more of a 0-3 byte decimal places. Datatime and Timestamp have several different storage footprint.

For convenience, we default Timestamp this article only need to use four bytes of storage space, but DateTime takes 8 bytes of storage space.

4. Numeric timestamp is the better choice?

In many cases, we will use the value int or bigint type is the time stamp to indicate the time.

Timestamp has such a storage type has several advantages, and its efficiency will be sorted by date, and other operations will be higher contrast, cross-system is also very convenient, but after all stored values. Disadvantages are also obvious, that is bad readability of data, you can not visually see specific time.

Timestamp is defined as follows:

Timestamp is defined from a reference time since the beginning of the reference time is "1970-1-1 00:00:00 +0: 00" From this time, as integers, time in seconds, over time, the passage of time integer increasing. As a result, I just need a number, you can perfectly represent time, and this value is an absolute value, that is, regardless of living in any corner of the earth, this represents the time stamp is the same, resulting values ​​are the same, and there is no concept of time zones, the time in the transmission system, no need for additional conversion, and only when the display to the user, it is converted to local time string format.

The actual database operations:

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

MySQL storage time in the end how to do? Datetime? Timestamp? Value stored timestamp?

As if there is no silver bullet, many programmers will find numeric timestamps are really good, high efficiency and also a variety of compatible, but many people also feel that it's not intuitive performance. Here insert a mouth, author of "High Performance MySQL" God, this book is recommended Timestamp, because the value represents the time not intuitive. Here is the text:

Each method has its own advantages, according to the actual scene is king. Here again these three ways to make a simple comparison, to choose the right storage time of the actual development of all types of data:

If you have any questions please give me a shout! If the article had any questions, but also take the trouble to point out, Guide brother grateful!

I will explain later in the article:

  • Support [] Java8 to date, and why not use SimpleDateFormat.
  • [] SpringBoot in how to actually use (JPA for example)

Open source projects recommended

On the recommendation of other open source projects:

  1. JavaGuide : Java learning [+] Interview Guide covers a majority of Java programmers need to master the core knowledge.
  2. Guide-springboot : suitable for beginners as well as experienced developers access to the Spring Boot tutorial (spare time maintenance, maintenance welcome together).
  3. Advancement-Programmer : I think the technical staff should have some good habits!
  4. -Security-jwt-the Spring Guide : Getting started from zero! Spring Security With JWT (including verification authority) a rear end part of the code.

the public

Guess you like

Origin juejin.im/post/5e1d494a5188254c45778a14