您建议使用datetime或timestamp字段吗?为什么(使用MySQL)?

我在服务器端使用PHP。


当前回答

在使用MySQL和PHP时,我总是使用Unix时间戳。这主要是因为PHP中的默认日期方法使用时间戳作为参数,因此不需要解析。

要获取PHP中当前的Unix时间戳,只需执行time();在MySQL中执行SELECT UNIX_TIMESTAMP();。

其他回答

TIMESTAMP需要4个字节,而DATETIME需要8个字节。

在使用MySQL和PHP时,我总是使用Unix时间戳。这主要是因为PHP中的默认日期方法使用时间戳作为参数,因此不需要解析。

要获取PHP中当前的Unix时间戳,只需执行time();在MySQL中执行SELECT UNIX_TIMESTAMP();。

我发现TIMESTAMP能够基于当前时间自动更新自己,而不使用不必要的触发器,这一点非常有用。虽然TIMESTAMP是UTC,但这只是我自己。

它可以跟踪不同的时区,因此如果您需要显示相对时间,例如UTC时间就是您想要的。

DATETIME类型用于包含日期和时间部分的值。MySQL以格式检索并显示DATETIME值。支持的范围为。'YYYY-MM-DD hh:MM:ss''1000-01-01 00:00:00''9999-12-31 23:59:59'

TIMESTAMP数据类型用于包含日期和时间部分的值。TIMESTAMP的范围从“1970-01-01 00:00:01”UTC到“2038-01-19 03:14:07”UTC。

mysql> SELECT col,
     >     CAST(col AT TIME ZONE INTERVAL '+00:00' AS DATETIME) AS ut
     >     FROM ts ORDER BY id;
+---------------------+---------------------+
| col                 | ut                  |
+---------------------+---------------------+
| 2020-01-01 10:10:10 | 2020-01-01 15:10:10 |
| 2019-12-31 23:40:10 | 2020-01-01 04:40:10 |
| 2020-01-01 13:10:10 | 2020-01-01 18:10:10 |
| 2020-01-01 10:10:10 | 2020-01-01 15:10:10 |
| 2020-01-01 04:40:10 | 2020-01-01 09:40:10 |
| 2020-01-01 18:10:10 | 2020-01-01 23:10:10 |
+---------------------+---------------------+

URL MySQL 8.0:https://dev.mysql.com/doc/refman/8.0/en/datetime.html

+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
|                                       TIMESTAMP                                       |                                 DATETIME                                 |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
| TIMESTAMP requires 4 bytes.                                                           | DATETIME requires 8 bytes.                                               |
| Timestamp is the number of seconds that have elapsed since January 1, 1970 00:00 UTC. | DATETIME is a text displays 'YYYY-MM-DD HH:MM:SS' format.                |
| TIMESTAMP supported range: ‘1970-01-01 00:00:01′ UTC to ‘2038-01-19 03:14:07′ UTC.    | DATETIME supported range: ‘1000-01-01 00:00:00′ to ‘9999-12-31 23:59:59′ |
| TIMESTAMP during retrieval converted back to the current time zone.                   | DATETIME can not do this.                                                |
| TIMESTAMP is used mostly for metadata i.e. row created/modified and audit purpose.    | DATETIME is used mostly for user-data.                                   |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+