(编辑:jimmy 日期: 2024/12/28 浏览:2)
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);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。