轉自:https://www.cnblogs.com/ycookie/p/5157760.html
偶然看到MySQL的一個函數 unix_timestamp(),不明就里,於是就試驗了一番。
unix_timestamp()函數的作用是返回一個確切的時間點的UNIX時間戳,這個Unix時間戳是一個無符號整數。 unix_timestamp()函數有兩種重載形式,一是不帶任何參數,另外一個是帶有一個Date或DateTime或TimeStamp類型的參 數。
unix_timestamp(),返回自1970-1-1 8:00:00開始到當前系統時間為止的秒數。
unix_timestamp(date),返回1970-1-1 8:00:00開始到date所代表的時間為止的秒數,對於早於1970-1-1 8:00:00的時間,總是返回 0 。
注意:因為中國是東八區,所以是8:00:00.
mysql> select unix_timestamp();
+------------------+
| unix_timestamp() |
+------------------+
| 1303195194 |
+------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp(current_timestamp());
+-------------------------------------+
| unix_timestamp(current_timestamp()) |
+-------------------------------------+
| 1303195204 |
+-------------------------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp('2011-4-19 12:00:00');
+--------------------------------------+
| unix_timestamp('2011-4-19 12:00:00') |
+--------------------------------------+
| 1303185600 |
+--------------------------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp('1970-1-1 6:00:00');
+------------------------------------+
| unix_timestamp('1970-1-1 6:00:00') |
+------------------------------------+
| 0 |
+------------------------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp('1970-1-1 8:00:00');
+------------------------------------+
| unix_timestamp('1970-1-1 8:00:00') |
+------------------------------------+
| 0 |
+------------------------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp('1970-1-1 8:00:01');
+------------------------------------+
| unix_timestamp('1970-1-1 8:00:01') |
+------------------------------------+
| 1 |
+------------------------------------+
1 row in set (0.00 sec)
mysql> select unix_timestamp('1970-1-1 8:01:00');
+------------------------------------+
| unix_timestamp('1970-1-1 8:01:00') |
+------------------------------------+
| 60 |
+------------------------------------+
1 row in set (0.00 sec)
了解了這個函數以后,就想如果知道了UNIX時間戳,如何換算成其對就的時間呢?於是想到了以下方法:
mysql> select date_add('1970-01-01 8:00:00',interval 1303191235 second);
+-----------------------------------------------------------+
| date_add('1970-01-01 8:00:00',interval 1303191235 second) |
+-----------------------------------------------------------+
| 2011-04-19 13:33:55 |
+-----------------------------------------------------------+
1 row in set (0.00 sec)
呵呵,沒有想到的是,MySQL也提供了一個函數,叫做 from_unixtime(unixtime),這個函數和上面那個函數表達式的結果完全相同:
mysql> select from_unixtime(1303191235);
+---------------------------+
| from_unixtime(1303191235) |
+---------------------------+
| 2011-04-19 13:33:55 |
+---------------------------+