How to get the second Thursday of a month in SQL Server?
For example:
- If the month is June 2016, I need to get the date
06/9/2016
- If the month is July 2016, I need to get the date
07/14/2016
How to get the second Thursday of a month in SQL Server?
For example:
06/9/2016
07/14/2016
SELECT
DATEADD (
DAY, (
DATEDIFF ( DAY, 3, --Day of week where 0 = Mon
DATEADD ( MONTH,
DATEDIFF ( MONTH, 0, GETDATE() ), 0
)
)
/ 7
) * 7 + ( 2 * 7 ), --1 * 7 for week 1, 2 * 7 for week 2, etc.
3 --Day of week where 0 = Mon
) AS NextDay
Replace GETDATE()
to what you want , it will return the first day of your provided date.
This will get the 1st, 2nd, 3rd etc. (@intIteration) Thursday (@strDay) starting at a specified date (@dtToday). You can pass any weekday to @strDay (e.g. 'Wednesday').
CREATE FUNCTION [dbo].[GetDateOnNthDayOfMonth]
(
@intIteration int = null,
@strDay varchar(9) = null,
@dtToday datetime = null
)
RETURNS datetime
AS
BEGIN
DECLARE @dtReturn datetime = NULL
DECLARE @dtDate datetime
SET @strDay = ISNULL(@strDay, 'Monday')
SET @dtToday = ISNULL(@dtToday,GETDATE())
SET @dtDate = @dtToday
SET @intIteration = ISNULL(@intIteration,1) - 1
WHILE @dtReturn IS NULL
BEGIN
IF DATENAME(WEEKDAY, @dtDate) = @strDay
SET @dtReturn = DATEADD(DAY, @intIteration * 7, @dtDate)
ELSE
SET @dtDate = DATEADD(DAY, 1, @dtDate)
END
RETURN @dtReturn
END
Use it like this:
SELECT dbo.GetDateOnNthDayOfMonth(2,'Thursday','2016-06-01')
SELECT dbo.GetDateOnNthDayOfMonth(2,'Thursday','2016-07-01')
SELECT dbo.GetDateOnNthDayOfMonth(4,'Wednesday','2020-06-15')
simple create a function and pass date to get desire Thursday date
CREATE FUNCTION Get2nd_ThursDay(@CurrentDate DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE @NextThursday DATETIME
SELECT @NextThursday = DATEADD(DAY, (DATEDIFF(DAY, 3,
DATEADD(MONTH, DATEDIFF(MONTH, 0, @CurrentDate), 0)) / 7) * 7 + 14, 3)
RETURN @NextThursday
END
then use in query as
SELECT dbo.Get2nd_ThursDay(getdate())
You can use following function:
CREATE FUNCTION fn_DayOfMonth
(
@date datetime,
@day [int],
@num int
)
RETURNS datetime
AS
BEGIN
DECLARE @desiredDate as datetime;
DECLARE @firstDate as datetime;
SELECT @firstDate = DATEADD(month, DATEDIFF(month, 0, @date), 0);
SELECT @desiredDate = DATEADD(DAY, ( ( (7 * @num + @day) - DATEPART(dw, @firstDate) ) % 7 ) + 7, @firstDate);
RETURN @desiredDate;
END
GO
And use it as follow:
SELECT [dbo].[fn_DayOfMonth]('2016-06-09', 5, 2)
Which first argument is the input date, second one is the day of the week (1 for Sunday and 7 for Sat) and the last argument is the occurrence.