每周的第一天日期

获取某周的第一天日期。
参考下面MS SQL Server代码:

 

CREATE FUNCTION [dbo].[svf_StartOfWeek]
(    
    @Year INT,
    @WK INT
)
RETURNS DATETIME
AS
BEGIN        
    DECLARE @FirstDayOfYear DATETIME = DATEFROMPARTS(@Year, 1, 1);
    DECLARE @IsFirstDayInFirstWeek INT = CASE WHEN (DATEPART(WEEKDAY, @FirstDayOfYear) <= 4) THEN 1 ELSE 0 END;     
    RETURN DATEADD(WEEK, @WK - @IsFirstDayInFirstWeek, DATEADD(DAY, (1 - DATEPART(WEEKDAY, @FirstDayOfYear)), @FirstDayOfYear));
END
Source Code

 
附加:获取某周最后一天:

CREATE FUNCTION [dbo].[svf_EndOfWeek]
(    
    @Year INT,
    @WK INT
)
RETURNS DATETIME
AS
BEGIN        
    DECLARE @FirstDayOfYear DATETIME = DATEFROMPARTS(@Year, 1, 1);
    DECLARE @IsFirstDayInFirstWeek INT = CASE WHEN (DATEPART(WEEKDAY, @FirstDayOfYear) <= 4) THEN 1 ELSE 0 END;     
    RETURN  DATEADD(WEEK, @WK - @IsFirstDayInFirstWeek, DATEADD(DAY, (@@DATEFIRST - DATEPART(WEEKDAY, @FirstDayOfYear)), @FirstDayOfYear));
END
GO
Source Code

 

以上2个函数,受到语言环境和@@DATEFIRST值的影响。

posted @ 2021-04-20 16:50  Insus.NET  阅读(116)  评论(0编辑  收藏  举报