MySQL根據年份的周數獲取該周起始時間


概述

做項目中,碰到了個難題:想要根據年份和第幾周獲取該周的周一和周日的時間。找了下MySQL中的日期函數,發現沒有。既然沒有輪子用,那我們自己造個輪子。

根據年份和周數獲取該周第一天的日期

-- 自定義函數
delimiter //
drop function if exists FUN_GET_FIRSTDATE_OF_WEEK;
create function FUN_GET_FIRSTDATE_OF_WEEK(years int,weeks int) returns varchar(32)
begin
	declare days int default 0;
	if weeks = 1 then
		return concat(years,'-01-01');
	elseif weeks >1 then
		select dayofweek(concat(years,'-01-01'))-2 into days;
		return makedate(years,weeks*7-days-6);
	else
		return null;
	end if ;
end//
delimiter ;

-- 函數調用
select FUN_GET_FIRSTDATE_OF_WEEK(2019,8)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注意:第一周的第一天存在跨年的問題,一般都是取1月1號

根據年份和周數獲取該周最后一天的日期

-- 自定義函數
delimiter //
drop function if exists FUN_GET_LASTDATE_OF_WEEK;
create function FUN_GET_LASTDATE_OF_WEEK(years int,weeks int) returns varchar(32)
begin
	declare days int default 0;
	if weeks * 7 >= 365 then 
		return concat(years,'-12-31');
	elseif weeks *7 < 365 and weeks *7 >0 then
		select dayofweek(concat(years,'-01-01'))-2 into days;
		return makedate(years,weeks*7-days);
	else
		return null;
	end if;	
end//
delimiter ;

-- 函數調用
select FUN_GET_LASTDATE_OF_WEEK(2020,1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注意:年份的最后一周不一定是周日,直接取12月31號即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM