Search code examples
sql-servert-sqldatedatediffdate-difference

SQL Server : get datediff for ISO weeks


Spent the better half of the day trying to figure this one out.

I want to get the datediff of two dates, based on their ISO week.

Here is my code:

SET DATEFIRST 1 ;   

DECLARE @A date, @B date;

SET @A = '20180829'; -- August 29th
SET @B = '20180902'; -- September 2nd

SELECT DATEDIFF(WW, @A, @B )

If you check: http://whatweekisit.org/ (Week 35, Year 2018) you can see that it runs August 27 to September 2.

The code above will return a DateDiff = 1, which should be 0. Trying to run DateDiff on ISO week just returns the following error:

The datepart iso_week is not supported by date function datediff

I've tried taking out the week dateparts from the dates, but then I get the problem when comparing dates from different years.

Is there a way around this?


Solution

  • SELECT DATEDIFF(ww, DATEADD(dd,-1, @A ), DATEADD(dd,-1,@B)) 
    --Seems to do the trick?
    

    Taken from: Number of weeks and partial weeks between two days calculated wrong

    Though I cannot see why the other post in the link adds a 1 at the end.