MySQL日期格式比较常用的两个函数是DATEDIFF()和TIMESTAMPDIFF()。
DATEDIFF
SELECT DATEDIFF('2023-12-31 23:59:59', '2023-12-30');# 1SELECT DATEDIFF('2023-11-30 23:59:59', '2023-12-31');# -31
第一个参数减去第二个参数得到的天数。
TIMESTAMPDIFF
SELECT TIMESTAMPDIFF(MONTH,'2023-02-01','2023-05-01');# 3SELECT TIMESTAMPDIFF(MONTH,'2023-05-01','2023-02-01');# -3SELECT TIMESTAMPDIFF(YEAR,'2023-01-01','2024-05-01');# 1SELECT TIMESTAMPDIFF(MINUTE,'2023-02-01','2023-05-01 12:05:55');# 128885
第三个参数减去第二个参数得到的对应日期类型数量,第一个参数是日期类型包括:
MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, 和 YEAR。
参考
datediff
timestampdiff