時間差函數(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
日期轉換計算函數(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);
