每週的第一天日期

Insus.NET發表於2021-04-20

獲取某周的第一天日期。
參考下面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值的影響。