Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Monday, Sunday based on a Week Number in SQL Server?

I have a week number (e.g. 23) and I'd like to get the dates for Monday and Sunday of that week.
I am assuming Monday as the first day of the week (e.g. I have SET DATEFIRST 1 in my script).

like image 469
AngryHacker Avatar asked Feb 02 '11 19:02

AngryHacker


2 Answers

DECLARE @startweek1 datetime
SET DATEFIRST 1

--first monday of year
SELECT @startweek1 = DATEADD(day, 8-DATEPART(weekday, '2011-01-01'), '2011-01-01')

--day based
SELECT
    DATEADD(day, 22 * 7, @startweek1) AS MondayWeek23,
    DATEADD(day, 23 * 7 -1 , @startweek1) AS SundayWeek23

--week based
SELECT
    DATEADD(week, 22, @startweek1) AS MondayWeek23,
    DATEADD(day, -1, DATEADD(week, 23 , @startweek1)) AS SundayWeek23

Edit:

This solution works if week 1 does not start on day 1 as Andomar said

Edit 2:

According to Wikipedia: 2008-12-29 is day 1 of week 1 of 2009 in ISO.

And week numbers vary as Andomar said

Cyberkiwi mentioned this code is wrong for 2007: it's wrong far more often than that. The same applies to his code too which matches 2007 but is equally wrong for the rest.

like image 164
gbn Avatar answered Sep 28 '22 08:09

gbn


Declare @StartDate datetime;
Set @StartDate = '20110101';

With StartOfWeek As
    (
    Select DateAdd(
        week
        , 23
        , DateAdd(
            d 
            , -(DatePart(dw, @StartDate) - 1)
            , @StartDate
            ) ) As Sunday
    )
Select Sunday, DateAdd(d,1,Sunday) As Monday
From StartOfWeek
like image 43
Thomas Avatar answered Sep 28 '22 08:09

Thomas