计算两个日期之间的间隔,可以使用DATEDIFF()函数
SELECT DATEDIFF('2010-06-01','2010-01-01'),DATEDIFF('2010-01-01','2010-06-01') 151 -151
注意:DATEDIFF函数也可以作用于date-and-time,但是它会忽略时间只显示天数
使用TIMEDIFF()函数计算出两个TIME类型之间的时间间隔
mysql> SELECT TIMEDIFF('12:12:12','11:11:11'); +---------------------------------+ | TIMEDIFF('12:12:12','11:11:11') | +---------------------------------+ | 01:01:01 | +---------------------------------+ 1 row in set (0.00 sec)
这里我添加一个TIMESTAMPDIFF(UNIT,TIME1,TIME2)函数
mysql> SET @D1 = '1999-09-09 12:11:11', @D2 = '2009-09-09 12:11:11'; Query OK, 0 rows affected (0.00 sec) mysql> SELECT TIMESTAMPDIFF(MINUTE,@D1,@D2), TIMESTAMPDIFF(DAY,@D1,@D2); +-------------------------------+----------------------------+ | TIMESTAMPDIFF(MINUTE,@D1,@D2) | TIMESTAMPDIFF(DAY,@D1,@D2) | +-------------------------------+----------------------------+ | 5260320 | 3653 | +-------------------------------+----------------------------+ 1 row in set (0.00 sec)
TIME_TO_SEC()
SELECT t1,t2,TIME_TO_SEC(t2) - TIME_TO_SEC(t1),TIME_TO_SEC(t1) - TIME_TO_SEC(t2) FROM time_val 05:01:30 02:30:20 -9070 9070 15:00:00 15:00:00 0 0 12:30:20 17:30:45 18025 -18025
TO_DAYS()