MySQL中可以使用几种函数来计算时间差:
TIMESTAMPDIFF() – 计算两个日期 / 时间之间的差值。
TIMEDIFF() – 计算两个时间之间的差值。
DATEDIFF() – 计算两个日期之间的差值。
下面是使用TIMESTAMPDIFF()函数计算两个日期之间的差值:
SELECT TIMESTAMPDIFF(SECOND, '2021-01-01 00:00:00', '2021-01-01 00:01:00') AS seconds_diff;
SELECT TIMESTAMPDIFF(MINUTE, '2021-01-01 00:00:00', '2021-01-01 00:02:30') AS minutes_diff;
SELECT TIMESTAMPDIFF(HOUR, '2021-01-01 00:00:00', '2021-01-01 01:30:00') AS hours_diff;
SELECT TIMESTAMPDIFF(DAY, '2021-01-01 00:00:00', '2021-01-03 00:00:00') AS days_diff;
SELECT TIMESTAMPDIFF(MONTH, '2021-01-01 00:00:00', '2021-03-01 00:00:00') AS months_diff;
SELECT TIMESTAMPDIFF(YEAR, '2021-01-01 00:00:00', '2023-01-01 00:00:00') AS years_diff;
使用TIMEDIFF()计算两个时间之间的差值:
SELECT TIMEDIFF('12:00:00', '10:30:00') AS time_diff;
使用DATEDIFF()函数计算两个日期之间的差值:
SELECT DATEDIFF('2021-01-01', '2020-12-25') AS date_diff;