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号即可

原文地址:https://www.cnblogs.com/adolfmc/p/13540362.html