1. 時(shí)間差函數(shù)(TIMESTAMPDIFF、DATEDIFF)
需要用MySQL計(jì)算時(shí)間差,使用TIMESTAMPDIFF、DATEDIFF,記錄一下實(shí)驗(yàn)結(jié)果
--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');
關(guān)于TIMESTAMPDIFF描述,見(jiàn)http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff
如需知道TIMESTAMPDIFF還能以哪些單位返回?cái)?shù)據(jù),可參考TIMESTAMPADD的描述:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampadd
2. 日期轉(zhuǎn)換計(jì)算函數(shù)(date_add、day、date_format、str_to_date)
-- 用日期與字符串轉(zhuǎn)換,計(jì)算當(dāng)月第一天、下月第一天
select curdate() as '當(dāng)前日期',
DATE_FORMAT(curdate(), '%Y-%m') as '當(dāng)前月份',
str_to_date(concat(DATE_FORMAT(curdate(), '%Y-%m'), '-01'), '%Y-%m-%d') as '當(dāng)前月的第一天',
date_add(str_to_date(concat(DATE_FORMAT(curdate(), '%Y-%m'), '-01'), '%Y-%m-%d'), interval 1 month) as '下月的第一天';
-- 當(dāng)前月的最后一天
select last_day(curdate());
-- 下月第一天
select date_add(last_day(curdate()), interval 1 day);
-- 當(dāng)天為當(dāng)月的第幾天
select day(curdate());
-- 當(dāng)月第一天
select date_add(curdate(), interval 1-(day(curdate())) day);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- MySQL的時(shí)間差函數(shù)TIMESTAMPDIFF、DATEDIFF的用法
- 實(shí)現(xiàn)MySQL + PostgreSQL批量插入更新insertOrUpdate
- MYSQL row_number()與over()函數(shù)用法詳解
- MySQL隱式類(lèi)型轉(zhuǎn)換導(dǎo)致索引失效的解決
- 淺談MySQL數(shù)據(jù)查詢(xún)太多會(huì)OOM嗎
- Django搭建MySQL主從實(shí)現(xiàn)讀寫(xiě)分離
- MySQL多表連接查詢(xún)?cè)斀?/li>
- mysql中TIMESTAMPDIFF案例詳解