mysql中的unix_timestamp函数
偶然看到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 |
+---------------------------+
1 row in set (0.00 sec)