【MYSQL】 DATEDIFF 与TIMESTAMPDIFF在计算相差天数时的区别

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的介绍。

需要注意的是:

  1. DATEDIFF使用时用第一个参数-第二个参数,TIMESTAMPDIFF则是用第二参数-第一个参数,两个刚好是相反的。
  2. 如果时间是YYYY-MM-DD HH:MM:SS 格式,在计算天数差时,TIMESTAMPDIFF使用的是24小时制,即使是23h59m59s,也不算做是一天。而DATEDIFF则是直接截取日期的部分相减。那么此时使用两个函数计算出来的天数是不一样的。如下图:

TIMESTAMPDIFF

在这里插入图片描述

DATEDIFF

在这里插入图片描述

在(1)计算日期的差(2)时间格式为YYYY-MM-DD HH:MM:SS时,使用两个函数的结果是不同的,需要根据具体的业务场景进行选择。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值