TLDR
- 在 Mysql 8 中使用 datetime
- 在 Mysql 5 中使用 bigint
辨析
timestamp
这种数据类型的时间范畴有限,基本被淘汰了,不要考虑。
datetime
在 mysql 5 中,datetime 只能存储年月日时分秒,并不能存储毫秒,不够精确。而在 mysql 8 中,datetime 可以存储毫秒,推荐使用。
bigint
使用整数来保存 unix 时间戳是一个好想法。编程语言中的时间戳支持到毫秒位,要在 mysql 中进行存储的话,int 型大小不够,需要使用 bigint 来保存。
1、bigint类型转换为datetime类型
假设 1164691264437 是 Java 里的“日期时间”:即:自1970-01-01 00:00:00以来的毫秒数
mysql> select from_unixtime(1164691264437/1000);
+-----------------------------------+
| from_unixtime(1164691264437/1000) |
+-----------------------------------+
| 2006-11-28 13:21:04 |
+-----------------------------------+
2、datetime类型转换为bigint类型
假设 "2011-05-31 23:59:59" 是 Java 里的“日期时间”:即:自1970-01-01 00:00:00以来的毫秒数
mysql> select UNIX_TIMESTAMP('2011-05-31 23:59:59');
+-----------------------------------+
| from_unixtime(1306857599/1000) |
+-----------------------------------+ |