DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part ‘00:00:00’ where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.
以上为官方文档对DATEDIFF 和TIMESTAMPDIFF的介绍。
需要注意的是:
- DATEDIFF使用时用第一个参数-第二个参数,TIMESTAMPDIFF则是用第二参数-第一个参数,两个刚好是相反的。
- 如果时间是YYYY-MM-DD HH:MM:SS 格式,在计算天数差时,TIMESTAMPDIFF使用的是24小时制,即使是23h59m59s,也不算做是一天。而DATEDIFF则是直接截取日期的部分相减。那么此时使用两个函数计算出来的天数是不一样的。如下图:
TIMESTAMPDIFF
DATEDIFF
在(1)计算日期的差(2)时间格式为YYYY-MM-DD HH:MM:SS时,使用两个函数的结果是不同的,需要根据具体的业务场景进行选择。