Mahmoud ElMansy: knowledge meant to be free

TSQL Number of Days In a Given Month

TSQL Number of Days In a Given Month.

The Following query will get the number of days in a month for a given date
this query will consider Leap years

--Declare Variable to set datetime
Declare @GivenDate DATETIME=getdate();

select CASE WHEN MONTH(@GivenDate) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(@GivenDate) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(@GivenDate) % 4 = 0 AND
YEAR(@GivenDate) % 100 != 0) OR
(YEAR(@GivenDate) % 400 = 0)
THEN 29
ELSE 28
END
END
GO
GO