当前位置:主页 > 数据库 > Mysql >

MySQL的时间差函数(TIMESTAMPDIFF、DATEDIFF)、日期转换计算函数(date_add、day、date_format、str_to_date)

时间:2021-03-07 10:29:39 | 栏目:Mysql | 点击:

1. 时间差函数(TIMESTAMPDIFF、DATEDIFF)

需要用MySQL计算时间差,使用TIMESTAMPDIFF、DATEDIFF,记录一下实验结果

--0
select datediff(now(), now());

--2
select datediff('2015-04-22 23:59:00', '2015-04-20 00:00:00');

--2
select datediff('2015-04-22 00:00:00', '2015-04-20 23:59:00');

--1
select TIMESTAMPDIFF(DAY, '2015-04-20 23:59:00', '2015-04-22 00:00:00');

--2
select TIMESTAMPDIFF(DAY, '2015-04-20 00:00:00', '2015-04-22 00:00:00');

--2
select TIMESTAMPDIFF(DAY, '2015-04-20 00:00:00', '2015-04-22 12:00:00');

--2
select TIMESTAMPDIFF(DAY, '2015-04-20 00:00:00', '2015-04-22 23:59:00');

--71
select TIMESTAMPDIFF(HOUR, '2015-04-20 00:00:00', '2015-04-22 23:00:00');

--4260
select TIMESTAMPDIFF(MINUTE, '2015-04-20 00:00:00', '2015-04-22 23:00:00');

关于TIMESTAMPDIFF描述,见http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff

如需知道TIMESTAMPDIFF还能以哪些单位返回数据,可参考TIMESTAMPADD的描述:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampadd

2. 日期转换计算函数(date_add、day、date_format、str_to_date)

-- 用日期与字符串转换,计算当月第一天、下月第一天
select curdate() as '当前日期', 
DATE_FORMAT(curdate(), '%Y-%m') as '当前月份', 
str_to_date(concat(DATE_FORMAT(curdate(), '%Y-%m'), '-01'), '%Y-%m-%d') as '当前月的第一天', 
date_add(str_to_date(concat(DATE_FORMAT(curdate(), '%Y-%m'), '-01'), '%Y-%m-%d'), interval 1 month) as '下月的第一天';

-- 当前月的最后一天
select last_day(curdate());

-- 下月第一天
select date_add(last_day(curdate()), interval 1 day);

-- 当天为当月的第几天
select day(curdate());

-- 当月第一天
select date_add(curdate(), interval 1-(day(curdate())) day);

您可能感兴趣的文章:

相关文章