Determine 3rd Friday of each month
Given:
- Friday is called "Friday"
The 3rd Friday of the month will always fall from 15th-21st of the month
select thedate from yourtable where datename(weekday, thedate) = 'Friday' and datepart(day, thedate)>=15 and datepart(day, thedate)<=21;
You could also use weekday
with datepart()
, but it's more readable with a name IMO. String comparisons will obviously be slower though.
In order to get a language/culture independent answer, you need to account for different weekday names and start of the week.
In Italy, Friday is "Venerdì" and the fisrt day of the week is Monday, not Sunday as in US.
1900-01-01
was a monday, so we can use this information to calculate the weekday in a locale-independent fashion:
WITH dates AS (
SELECT DATEADD(day, number, GETDATE()) AS theDate
FROM master.dbo.spt_values
WHERE type = 'P'
)
SELECT theDate, DATENAME(dw, theDate), DATEPART(dw, theDate)
FROM dates
WHERE DATEDIFF(day, '19000101', theDate) % 7 = 4
AND DATEPART(day, thedate)>=15 and DATEPART(day, thedate)<=21;
Another way, that uses Phil's answer as a base, and takes care of different setting:
select thedate
from yourtable
where (datepart(weekday, thedate) + @@DATEFIRST - 2) % 7 + 1 = 5 -- 5 -> Friday
and (datepart(day, thedate) - 1) / 7 + 1 = 3 ; -- 3 -> 3rd week
The 5
code (if you want a weekday other than Friday) should be (the same as SET DATEFIRST
codes):
1 for Monday
2 for Tuesday
3 for Wednesday
4 for Thursday
5 for Friday
6 for Saturday
7 for Sunday
You can also just use a "known good" date to be safe in the face of language settings. For example, if looking for Fridays, check a calendar and see that January 2nd 2015 was a Friday. The first comparison could then be written as:
DATEPART(weekday,thedate) = DATEPART(weekday,'20150102') --Any Friday
See also How to get the Nth weekday of a month by Peter Larsson.