獲得當前日期+時間(date + time)函數:now()
| mysql> select now();+---------------------+| now() |+---------------------+| 2008-08-08 22:20:46 |+---------------------+ |
獲得當前日期+時間(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 |+---------------------+----------+---------------------+ |
sysdate() 日期時間函數,一般情況下很少用到。
MySQL 獲得當前時間戳函數:current_timestamp, current_timestamp()
| mysql> select current_timestamp, current_timestamp();+---------------------+---------------------+| current_timestamp | current_timestamp() |+---------------------+---------------------+| 2008-08-09 23:22:24 | 2008-08-09 23:22:24 |+---------------------+---------------------+ |
MySQL 日期轉換函數、時間轉換函數
MySQL Date/Time to Str(日期/時間轉換為字符串)函數:date_format(date,format), time_format(time,format)
| mysql> select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');+----------------------------------------------------+| date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s') |+----------------------------------------------------+| 20080808222301 |+----------------------------------------------------+ |
MySQL 日期、時間轉換函數:date_format(date,format), time_format(time,format) 能夠把一個日期/時間轉換成各種各樣的字符串格式。它是 str_to_date(str,format) 函數的 一個逆轉換。
MySQL Str to Date (字符串轉換為日期)函數:str_to_date(str, format)
| select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09select str_to_date('08/09/08' , '%m/%d/%y'); -- 2008-08-09select str_to_date('08.09.2008', '%m.%d.%Y'); -- 2008-08-09select str_to_date('08:09:30', '%h:%i:%s'); -- 08:09:30select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30 |
可以看到,str_to_date(str,format) 轉換函數,可以把一些雜亂無章的字符串轉換為日期格式。另外,它也可以轉換為時間。“format” 可以參看 MySQL 手冊。
MySQL (日期、天數)轉換函數:to_days(date), from_days(days)
| select to_days('0000-00-00'); -- 0select to_days('2008-08-08'); -- 733627 |
MySQL (時間、秒)轉換函數:time_to_sec(time), sec_to_time(seconds)
| select time_to_sec('01:00:05'); -- 3605select sec_to_time(3605); -- '01:00:05' |