datediff
功能
计算两个日期的差值,结果精确到天。
expr1
和 expr2
参数必须是合法的日期或日期/时间表达式。
此函数与 days_diff 的区别是:
函数名 | 行为 | 例子 |
---|---|---|
datediff | 对日期的判断精确到天级。 | '2020-12-25 23:00:00' 与 '2020-12-24 23:00:01' 的 datediff 为 1。 |
days_diff | 对日期的判断精确到秒级,并向下取整数。 | '2020-12-25 23:00:00' 与 '2020-12-24 23:00:01' 的 days_diff 为 0。 |
语法
INT DATEDIFF(DATETIME expr1,DATETIME expr2)
示例
select datediff(CAST('2007-12-31 23:59:59' AS DATETIME), CAST('2007-12-30' AS DATETIME));
+-----------------------------------------------------------------------------------+
| datediff(CAST('2007-12-31 23:59:59' AS DATETIME), CAST('2007-12-30' AS DATETIME)) |
+-----------------------------------------------------------------------------------+
| 1 |
+-----------------------------------------------------------------------------------+
select datediff(CAST('2010-11-30 23:59:59' AS DATETIME), CAST('2010-12-31' AS DATETIME));
+-----------------------------------------------------------------------------------+
| datediff(CAST('2010-11-30 23:59:59' AS DATETIME), CAST('2010-12-31' AS DATETIME)) |
+-----------------------------------------------------------------------------------+
| -31 |
+-----------------------------------------------------------------------------------+