In SQL Server, there’s a buildin function to calculate the number of weeks between two dates. This function is called “DateDiff”. The problem with this function is that Sql Server thinks the week starts on sunday. Maybe this it true in some situations but at my current project, the week should start on monday. This article gives you more info how to fix the issue with the datediff and weeks.
SELECT DATEDIFF(wk,'2012-01-07', '2012-01-08')
7th of January is saturday, 8th of January is sunday. The answer from SQL Server is 1. That’s true because the new week starts on sunday.
Ok the problem is clear. How can I fix this problem? After doing some research, I found an article about Visual Basic. In VB, there’s a simular function to calculate with dates:
DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])
Unfortunately, this last argument isn’t available in Sql Server. So looking around on the internet, I found this.
SET LANGUAGE Dutch
Specifies the language environment for the session. The session language determines the datetime formats and system messages.
After running this SET LANGUAGE command, I run the DateDiff command again:
SELECT DATEDIFF(wk,CAST('2012-01-07' AS DATETIME), CAST('2012-01-08' AS DATETIME) )
And the answer? 4. I don’t understand this. How can this be possible? I think because in Dutch, the date notation is YYYYDDMM so SQL server thinks that I mean July – August and then the answer is correct.
When I reverse the month and day:
SELECT DATEDIFF(wk,CAST('2012-07-01' AS DATETIME), CAST('2012-08-01' AS DATETIME) )
I get the answer: 1. Conclusion: this function will ignore the language setting and always perform the calculation assuming Sunday as the first day of the week.
This is also interesting; when I cast an integer to datetime, the language setting will be ignored:
There is a workaround for this issue. I found the function @@DATEFIRST. I never have used this one before. Try this:
SET LANGUAGE Dutch SELECT @@DATEFIRST; SET LANGUAGE us_english SELECT @@DATEFIRST;
This function returns a number, the first day of the week. In the Netherlands, it is 1. This means monday. In US, it’s 7 and means sunday. So by knowing this, I can create a nice statement to do the calculation.
SET LANGUAGE Dutch; SELECT DATEDIFF( week, DATEADD(DAY, -@@DATEFIRST, '20091227'), DATEADD(DAY, -@@DATEFIRST, '20091228') );
Answer: 1 = Correct.
Easy way: we know that @@DATEFIRST always returns 1 in my situation. So this also works:
SELECT DATEDIFF( week, DATEADD(DAY, -1, '20120108'), DATEADD(DAY, -1, '20120109') ) AS WeekDifference;
Friday to Saturday becomes Thursday to Friday: Difference = 0 weeks (before: 0 weeks)
Saturday to Sunday becomes Friday to Saturday: Difference = 0 weeks (before: 1 week)
Sunday to Monday becomes Saturday to Sunday: Difference = 1 weeks (before: 0 week)
Hope this helps you implementing the DateDiff function.