Week number in a Month

Tagged:

This is sample code. Add error handling and adjust to your requirements as necessary.

DECLARE @dt DATETIME, @WeekOfMonth TINYINT
SET @dt = '2007-07-08'
 
SET @WeekOfMonth = (DAY(@dt) + 
				(DATEPART(dw, DATEADD (MONTH, DATEDIFF (MONTH, 0, @dt), 0)) 
				  --^-- The day of the week for the first day of month
			-1) -- # of days to add to make the first week full 7 days
		-1)/7 + 1 
PRINT @WeekOfMonth

Try this too:

DECLARE @dt DATETIME, @WeekOfMonth TINYINT
SET @dt = '2007-07-08'
SET @WeekOfMonth = DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, @dt), 0), @dt) +1
PRINT @WeekOfMonth

Yes, it's shorter and simpler.

Thanks.