MySQL--TIMESTAMPDIFF函数

TIMESTAMPDIFF() function


用于返回两个时间点跨越的时间间隔,其中表示时间的单位可以自定义,有:秒、分钟、小时、天、周、月、年等等。

MySQL the TIMESTAMPDIFF() returns a value after subtracting a datetime expression from another.

It is not necessary that both the expression are of the same type. One may be a date and another is datetime. A date value is treated as a datetime with a default time part '00:00:00'. The unit for the result is given by another argument.

The unit should be one of the following : FRAC_SECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

Syntax :

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2);

Arguments :

Name Description
datetime_expr1 A datetime expression.
datetime_expr1 A datetime expression.
unit An unit, as described in the description.

代码实例:

测试数据:

 

1

0

310211111

test

021-111111

test1

10012551111

1

111

2017-04-11 18:41:13

34111

2017-07-21 13:56:58

 

1

1

2323

2

211

2016-11-08 18:54:01

111

2017-05-18 20:25:43

 

 

 

 

测试代码:

1.计算相差的天数

SELECTuid,subtime,chktime,TIMESTAMPDIFF(DAY,subtime,chktime) FROM `user_info` whereuid=1

 

uid

subtime

chktime

TIMESTAMPDIFF(DAY,subtime,chktime)

1

2017-04-11 18:41:13

2017-07-21 13:56:58

100

1

2016-11-08 18:54:01

2017-05-18 20:25:43

191

 

2.计算相差的年数

SELECTuid,subtime,chktime,TIMESTAMPDIFF(YEAR,subtime,chktime) FROM `user_info` whereuid=1

uid

subtime

chktime

TIMESTAMPDIFF(YEAR,subtime,chktime)

1

2017-04-11 18:41:13

2017-07-21 13:56:58

0

1

2016-11-08 18:54:01

2017-05-18 20:25:43

0

 

 

3.计算相差的月数

SELECTuid,subtime,chktime,TIMESTAMPDIFF(MONTH,subtime,chktime) FROM `user_info` whereuid=1

uid

subtime

chktime

TIMESTAMPDIFF(MONTH,subtime,chktime)

1

2017-04-11 18:41:13

2017-07-21 13:56:58

3

1

2016-11-08 18:54:01

2017-05-18 20:25:43

                                                                                    6

 

 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值