这几天写代码,反复用到将日期时间字段转化成数字串和日期格式字符串的情况,感觉自己还处于壹知半解之中,索性花点时间查下相关资料,基本弄明白了 MySQL 中两个常用的日期函数的用法,记录于此,作为笔记供参考。
1、FROM_UNIXTIME( unix_timestamp )mysql> select FROM_UNIXTIME(1344887103); +---------------------------+ | FROM_UNIXTIME(1344887103) | +---------------------------+ | 2012-08-14 03:45:03 | +---------------------------+ 1 row in set (0.00 sec)2、FROM_UNIXTIME( unix_timestamp ,format )
mysql> select FROM_UNIXTIME(1344887103,'%Y-%M-%D %h:%i:%s'); +-----------------------------------------------+ | FROM_UNIXTIME(1344887103,'%Y-%M-%D %h:%i:%s') | +-----------------------------------------------+ | 2012-August-14th 03:45:03 | +-----------------------------------------------+ 1 row in set (0.00 sec) mysql> select FROM_UNIXTIME(1344887103,'%Y-%m-%D %h:%i:%s'); +-----------------------------------------------+ | FROM_UNIXTIME(1344887103,'%Y-%m-%D %h:%i:%s') | +-----------------------------------------------+ | 2012-08-14th 03:45:03 | +-----------------------------------------------+ 1 row in set (0.00 sec)
参考链接:https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_from-unixtime
1、UNIX_TIMESTAMP()
返回值:当前时间的UNIX格式数字串,或者说是 UNIX 时间戳(从 UTC 时间'1970-01-01 00:00:00'开始的秒数),通常为十位,如 1344887103。
mysql> select unix_timestamp(); +------------------+ | unix_timestamp() | +------------------+ | 1344887103 | +------------------+ 1 row in set (0.00 sec)2、UNIX_TIMESTAMP( date )
mysql> SELECT UNIX_TIMESTAMP(); +------------------+ | UNIX_TIMESTAMP() | +------------------+ | 1344888895 | +------------------+ 1 row in set (0.00 sec) mysql> SELECT UNIX_TIMESTAMP('2012-08-14 16:19:23'); +---------------------------------------+ | UNIX_TIMESTAMP('2012-08-14 16:19:23') | +---------------------------------------+ | 1344932363 | +---------------------------------------+ 1 row in set (0.00 sec)
注意:如果你使用 UNIX_TIMESTAMP() 和 FROM_UNIXTIME() 来转换 TIMESTAMP 值与 Unix 时间戳的值,精度会丢失,因为这个映射在两个方向上不是一一对应的。比如说,由于本地时区的更改,有可能两个 UNIX_TIMESTAMP() 会映射到同壹个 Unix 时间戳的值。 FROM_UNIXTIME() 只会映射到原来的那个时间戳的值上。这里有个例子,在 CET 时区使用 TIMESTAMP:
mysql> SELECT UNIX_TIMESTAMP('2005-03-27 03:00:00'); +---------------------------------------+ | UNIX_TIMESTAMP('2005-03-27 03:00:00') | +---------------------------------------+ | 1111885200 | +---------------------------------------+ mysql> SELECT UNIX_TIMESTAMP('2005-03-27 02:00:00'); +---------------------------------------+ | UNIX_TIMESTAMP('2005-03-27 02:00:00') | +---------------------------------------+ | 1111885200 | +---------------------------------------+ mysql> SELECT FROM_UNIXTIME(1111885200); +---------------------------+ | FROM_UNIXTIME(1111885200) | +---------------------------+ | 2005-03-27 03:00:00 | +---------------------------+
参考链接: https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp