MySQL time type

MySQL time type

首先可以将使用字符串类型来表示时间类型排除掉:
   字符串占用需要 19字节,占用的空间比较大。
   其次字符串表示的时间比较、处理比较麻烦,不能使用时间函数,比如:YEAR()

Therefore, the commonly used time types in MySQL are TimeStamp and DateTime.

The difference between TimeStamp and DateTime:

Similarities :

  • The format of both is the same: YYYY-MM-DD HH:MM:SS

difference:

  1. DATETIME can be used in a wider time range

    1. The range that DATETIME can represent: 1000-01-01 00:00:00.000000to9999-12-31 23:59:59.999999

    2. The range that TIMESTAMP can represent:: '1970-01-01 00:00:01.000000' UTCto'2038-01-09 03:14:07.999999' UTC

      If the inserted time range exceeds the TIMESTAMP range, an error will be thrown.Incorrect datetime value: '2040-3-30 11:00:00' for column 'time_stamp'

  2. space occupied

    1. TIMESTAMP takes up 4 bytes
    2. DATETIME occupies 8 bytes in MySQL 5.6 and 5 bytes in later versions.
  3. The TIMESTAMP type is affected by time zone and will change with time zone changes.

    For example, the time_test table contains the following data:
    Insert image description here
    Change the system's time zone (the default is East 8, now change the system's time zone to East 9):
    Insert image description here

    Query the data in the table again and find that the time of type TIMESTAMP has changed, but the time of DATETIME has not changed:
    Insert image description here

  4. Insert now() and check whether the actual value saved is consistent with the current computer time:

    • TIMESTAMP: may be inconsistent because its value will first be converted to a UTC time value and then stored in the database
    • DATETIME: No conversion will be done, it is consistent with the current time.

summary:

  • TIMESTAMP takes up less space and is usually used in scenarios related to time zones. Of course, DATETIME can also be associated with time zones through some means;
  • The flaw of TIMESTAMP is that the time range it can represent is too small. DATETIME is usually used in scenarios that have nothing to do with time zones and requires a relatively large time range.

Guess you like

Origin blog.csdn.net/qq_50876039/article/details/127192403