> select period_add(200808,2), period_add(20080808,-2) +----------------------+-------------------------+| period_add(200808,2) | period_add(20080808,-2) |+----------------------+-------------------------+| 200810 | 20080806 |+----------------------+-------------------------+ MySQL period_diff(P1,P2):日期 P1-P2,返回 N 个月。mysql> select period_diff(200808, 200801); +-----------------------------+| period_diff(200808, 200801) |+-----------------------------+| 7 |+-----------------------------+ 在 MySQL 中,这两个日期函数,一般情况下很少用到。4. MySQL 日期、时间相减函数:datediff(date1,date2), timediff(time1,time2)MySQL datediff(date1,date2):两个日期相减 date1 - date2,返回天数。select datediff('2008-08-08', '2008-08-01'); -- 7select datediff('2008-08-01', '2008-08-08'); -- -7 MySQL timediff(time1,time2):两个日期相减 time1 - time2,返回 time 差值。select timediff('2008-08-08 08:08:08', '2008-08-08 00:00:00'); -- 08:08:08select timediff('08:08:08', '00:00:00'); -- 08:08:08 注意:timediff(time1,time2) 函数的两个参数类型必须相同。 四、MySQL 日期转换函数、时间转换函数1. MySQL (时间、秒)转换函数:time_to_sec(time), sec_to_time(seconds)select time_to_sec('01:00:05'); -- 3605select sec_to_time(3605); -- '01:00:05' 2. MySQL (日期、天数)转换函数:to_days(date), from_days(days)select to_days('0000-00-00'); -- 0select to_days('2008-08-08'); -- 733627 select from_days(0); -- '0000-00-00'select from_days(733627); -- '2008-08-08' 3. 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 手册。4. MySQL Date/Time to Str(日期/时间转换为字符串)函数:date_format(date,format), time_format(time,format)mysql> select date_format('2008-08-08 22:23:00', '%W %M %Y'); +------------------------------------------------+| date_format('2008-08-08 22:23:00', '%W %M %Y') |+------------------------------------------------+| Friday August 2008 |+------------------------------------------------+ 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 |+----------------------------------