DATEDIFF()函数返回两个日期之间的时间
DATEDIFF(datepart,startdate,enddate)
-- 获取两个日期之间的天数 SELECT DATEDIFF(day,'2021-01-01','2021-06-10') AS days; SELECT DATEDIFF(day,'2021-01-01 08:00:00','2021-06-10 09:00:00') AS days;
-- 获取两个日期之间的月数 SELECT DATEDIFF(month,'2021-01-01','2021-06-10') AS months; SELECT DATEDIFF(month,'2021-01-01 08:00:00','2021-06-10 09:00:00') AS months;
-- 获取两个日期之间的年数 SELECT DATEDIFF(year,'2021-01-01','2022-06-10') AS years; SELECT DATEDIFF(year,'2021-01-01 08:00:00','2022-06-10 09:00:00') AS years;
-- startdate位置0表示1900-01-01,-1表示1899-12-31 SELECT DATEDIFF(day, 0, '1900-01-01');-- 结果:0 SELECT DATEDIFF(day, 0, '1900-01-31');-- 结果:30 SELECT DATEDIFF(day, -1, '1900-01-01');-- 结果:1 SELECT DATEDIFF(day, -1, '1900-01-31');-- 结果:31