一、计算时间差
1、按照单位计算时间差 TIMESTAMPDIFF()
SELECT TIMESTAMPDIFF(YEAR, ‘2010-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(QUARTER, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(MONTH, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(WEEK, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(DAY, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(HOUR, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(MINUTE, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(SECOND, ‘2020-10-01 00:00:00’, NOW());
SELECT TIMESTAMPDIFF(MICROSECOND, ‘2020-10-01 00:00:00’, NOW());
2、两个日期相减 date1 – date2,返回天数 DATEDIFF()
SELECT DATEDIFF(NOW(), ‘2020-10-01 00:00:00’);
SELECT DATEDIFF(NOW(), ‘2020-10-01 11:00:12’);
3、两个日期相减 time1 – time2,返回 time 差值 TIMEDIFF()
SELECT TIMEDIFF(NOW(), ‘2020-10-01 00:00:00’);
注意:timediff(time1,time2) 函数的两个参数类型必须相同。
二、为日期增加一个时间间隔:date_add()
select date_add(NOW(), interval 1 day); -- add 1 day
select date_add(NOW(), interval 1 hour); -- add 1 hour
select date_add(NOW(), interval 1 minute); -- ...
select date_add(NOW(), interval 1 second);
select date_add(NOW(), interval 1 microsecond);
select date_add(NOW(), interval 1 week);
select date_add(NOW(), interval 1 month);
select date_add(NOW(), interval 1 quarter);
select date_add(NOW(), interval 1 year);
select date_add(NOW()
, interval -1 day);
三、为日期减去一个时间间隔:date_sub()
用法与date_add()类似
select date_sub(NOW(), interval ‘1 1:1:1′ day_second);
四、mysql其他日期:
1、period_add(P,N):日期加/减去N月
select period_add(200808,2), period_add(20080808,-2);
2、period_diff(P1,P2):日期 P1-P2,返回 N 个月。
select period_diff(200808, 200801);