Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Convert Week Number to Date (dd/MM)

I am trying to convert the week number (for example: 21) in SQL-Server to the date (from the Monday of that week) in dd/MM format.

I have searched online but cannot seem to find anything that I could use.

Is this something I can do?

Any help or advice is appreciated.

Thank you in advance.

like image 405
holodan Avatar asked May 27 '16 10:05

holodan


2 Answers

Try this,

declare @wk int  set @wk = 21
declare @yr int  set @yr = 2016

select dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4 -
       datepart(dw, dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4) + 1

or try this way

declare @wk int  = 21

select dateadd(week,@wk-1, DATEADD(wk, DATEDIFF(wk,-1,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)), 0)) 
like image 70
bmsqldev Avatar answered Sep 28 '22 21:09

bmsqldev


You can do it something like:

declare @Week_Number int, @Year int, @Year_Start_Day date, @Week_Day date

select 
    @Week_Number = 1,
    @Year = 2016

select @Year_Start_Day = cast(@Year as nvarchar(4)) + '0101'
select @Week_Day =  dateadd(wk, @Week_Number, @Year_Start_Day)

select dateadd(dd, 1 - datepart(weekday, @Week_Day), @Week_Day)
like image 33
Andrey Korneyev Avatar answered Sep 28 '22 22:09

Andrey Korneyev