标签:blog nbsp date_sub 结束 arch mys 开始 now() _for
1、mysql DAYOFWEEK 和 WEEKDAY获取星期
在mysql中,我们可以用DAYOFWEEK 和 WEEKDAY函数获取指定日期的星期。区别在于DAYOFWEEK获取的星期索引是以1开始,而WEEKDAY获取的星期索引是以0开始.
DAYOFWEEK(date)
返回日期date的星期索引(1=星期天,2=星期一, ……7=星期六)。这些索引值对应于ODBC标准。
mysql> select DAYOFWEEK(‘1998-02-03‘);
-> 3
WEEKDAY(date)
返回date的星期索引(0=星期一,1=星期二, ……6= 星期天)。
mysql> select WEEKDAY(‘1997-10-04 22:23:00‘);
-> 5
mysql> select WEEKDAY(‘1997-11-05‘);
-> 2
-- 今天
SELECT DATE_FORMAT(NOW(),‘%Y-%m-%d 00:00:00‘) AS ‘今天开始‘;
SELECT DATE_FORMAT(NOW(),‘%Y-%m-%d 23:59:59‘) AS ‘今天结束‘;
-- 昨天
SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 DAY), ‘%Y-%m-%d 00:00:00‘) AS ‘昨天开始‘;
SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 DAY), ‘%Y-%m-%d 23:59:59‘) AS ‘昨天结束‘;
-- 上周
SELECT DATE_FORMAT( DATE_SUB( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY), INTERVAL 1 WEEK), ‘%Y-%m-%d 00:00:00‘) AS ‘上周一‘;
SELECT DATE_FORMAT( SUBDATE(CURDATE(), WEEKDAY(CURDATE()) + 1), ‘%Y-%m-%d 23:59:59‘) AS ‘上周末‘;
-- 本周
SELECT DATE_FORMAT( SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),‘%w‘)-1), ‘%Y-%m-%d 00:00:00‘) AS ‘本周一‘;
SELECT DATE_FORMAT( SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),‘%w‘)-7), ‘%Y-%m-%d 23:59:59‘) AS ‘本周末‘;
-- 上面的本周算法会有问题,因为mysql是按照周日为一周第一天,如果当前是周日的话,会把时间定为到下一周.
SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY), ‘%Y-%m-%d 00:00:00‘) AS ‘本周一‘;
SELECT DATE_FORMAT( DATE_ADD(SUBDATE(CURDATE(), WEEKDAY(CURDATE())), INTERVAL 6 DAY), ‘%Y-%m-%d 23:59:59‘) AS ‘本周末‘;
-- 上月
SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 MONTH), ‘%Y-%m-01 00:00:00‘) AS ‘上月初‘;
SELECT DATE_FORMAT( LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)), ‘%Y-%m-%d 23:59:59‘) AS ‘上月末‘;
-- 本月
SELECT DATE_FORMAT( CURDATE(), ‘%Y-%m-01 00:00:00‘) AS ‘本月初‘;
SELECT DATE_FORMAT( LAST_DAY(CURDATE()), ‘%Y-%m-%d 23:59:59‘) AS ‘本月末‘;
mysql 日期函数
标签:blog nbsp date_sub 结束 arch mys 开始 now() _for
原文地址:https://www.cnblogs.com/cmw1024/p/14211927.html