[轉]MySQL 中 時間和日期函數

源地址:http://www.cnblogs.com/redfox241/archive/2009/07/23/1529092.html

 

==========================================================================================

一、MySQL 獲得當前日期時間 函數

1.1 獲得當前日期+時間(date + time)函數:now()

mysql
> select now();

+---------------------+
| now()               |
+---------------------+
| 2008-08-08 22:20:46 |
+---------------------+

除了 now() 函數能獲得當前的日期時間外,MySQL 中還有下面的函數:

 
current_timestamp()
,
current_timestamp
,localtime()
,localtime
,localtimestamp    
-- (v4.0.6)
,localtimestamp()  -- (v4.0.6)

這些日期時間函數,都等同於 now()。鑑於 now() 函數簡短易記,建議總是使用 now() 來替代上面列出的函數。

1.2 獲得當前日期+時間(date + time)函數:sysdate()

sysdate() 日期時間函數跟 now() 類似,不同之處在於:now() 在執行開始時值就得到了, sysdate() 在函數執行時動態得到值。看下面的例子就明白了:

mysql
> select now(), sleep(3), now();

+---------------------+----------+---------------------+
| now()               | sleep(3| now()               |
+---------------------+----------+---------------------+
| 2008-08-08 22:28:21 |        0 | 2008-08-08 22:28:21 |
+---------------------+----------+---------------------+

mysql
> select sysdate(), sleep(3), sysdate();

+---------------------+----------+---------------------+
| sysdate()           | sleep(3| sysdate()           |
+---------------------+----------+---------------------+
| 2008-08-08 22:28:41 |        0 | 2008-08-08 22:28:44 |
+---------------------+----------+---------------------+

可以看到,雖然中途 sleep 
3 秒,但 now() 函數兩次的時間值是相同的; sysdate() 函數兩次得到的時間值相差 3 秒。MySQL Manual 中是這樣描述 sysdate() 的:Return the time at which the function executes。

sysdate() 日期時間函數,一般情況下很少用到。

2. 獲得當前日期(date)函數:curdate()

mysql
> select curdate();

+------------+
| curdate()  |
+------------+
| 2008-08-08 |
+------------+

其中,下面的兩個日期函數等同於 curdate():

 
current_date()
,
current_date

3. 獲得當前時間(time)函數:curtime()

mysql
> select curtime();

+-----------+
| curtime() |
+-----------+
| 22:41:30  |
+-----------+

其中,下面的兩個時間函數等同於 curtime():

 
current_time()
,
current_time

4. 獲得當前 UTC 日期時間函數:utc_date(), utc_time(), utc_timestamp()

mysql
> select utc_timestamp(), utc_date(), utc_time(), now()

+---------------------+------------+------------+---------------------+
| utc_timestamp()     | utc_date() | utc_time() | now()               |
+---------------------+------------+------------+---------------------+
| 2008-08-08 14:47:11 | 2008-08-08 | 14:47:11   | 2008-

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章