SQL Convert Week Number to Date (dd/MM)

后端 未结 4 2012
一向
一向 2020-12-07 02:05

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.

相关标签:
4条回答
  • 2020-12-07 02:31

    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)) 
    
    0 讨论(0)
  • 2020-12-07 02:37

    How about this?

    DECLARE @YearNum SMALLINT = 2016;
    DECLARE  @WeekNum TINYINT=25;
    
    select 
        SUBSTRING(CONVERT(VARCHAR(10),selected_date,105),0,6) AS WeeKDate
    from 
    (select DATEADD(dd,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i,'1970-01-01') selected_date from
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
    where YEAR(selected_date)=@YearNum
    AND DATEPART(WK,selected_date)=@WeekNum
    AND DATEPART(WEEKDAY,selected_date)=2 -- Monday
    
    0 讨论(0)
  • 2020-12-07 02:40

    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)
    
    0 讨论(0)
  • 2020-12-07 02:53

    This will do:

    DECLARE @y int = 2016,
            @w int = 21
    
    SELECT CONVERT(nvarchar(5),DATEADD(day,@w*7-(DATEPART(WEEKDAY,CAST(@y as nvarchar(4))+'-01-01')-2),CAST(@y as nvarchar(4))+'-01-01'),3)
    

    Output:

    23/05
    
    0 讨论(0)
提交回复
热议问题