這幾天寫代碼,反覆用到將日期時間字段轉化成數字串和日期格式字符串的狀況,感受本身還處於壹知半解之中,索性花點時間查下相關資料,基本弄明白了 MySQL 中兩個經常使用的日期函數的用法,記錄於此,做爲筆記供參考。 html
一、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)二、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 mysql
一、UNIX_TIMESTAMP() sql
返回值:當前時間的UNIX格式數字串,或者說是 UNIX 時間戳(從 UTC 時間'1970-01-01 00:00:00'開始的秒數),一般爲十位,如 1344887103。 服務器
mysql> select unix_timestamp(); +------------------+ | unix_timestamp() | +------------------+ | 1344887103 | +------------------+ 1 row in set (0.00 sec)二、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 spa