Search

Saturday, April 2, 2011

Number of days in a month

Solution 1
DECLARE @Date datetime
SET @Date = '2000/02/1'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the week'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 7),@Date) AS 'Last day of the week'
SELECT DAY(DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS 'No of Days in the month'

Solution 2
DECLARE @d DATETIME
SET @d = '2003-02-1'
select datepart(dd, dateadd(dd, -(datepart(dd, dateadd(mm, 1, @d))),dateadd(mm, 1, @d))) AS 'No of Days in the month'

Solution 3
DECLARE @d DATETIME
SET @d = '2000-02-1'
SELECT CASE WHEN MONTH(@d) = 1
THEN 31
WHEN MONTH(@d) = 2
THEN CASE WHEN (YEAR(@d) % 4 = 0 AND YEAR(@d) % 100 <> 0) OR
YEAR(@d) % 400 = 0
THEN 29
ELSE 28
END
WHEN MONTH(@d) = 3
THEN 31
WHEN MONTH(@d) = 4
THEN 30
WHEN MONTH(@d) = 5
THEN 31
WHEN MONTH(@d) = 6
THEN 30
WHEN MONTH(@d) = 7
THEN 31
WHEN MONTH(@d) = 8
THEN 31
WHEN MONTH(@d) = 9
THEN 30
WHEN MONTH(@d) = 10
THEN 31
WHEN MONTH(@d) = 11
THEN 30
WHEN MONTH(@d) = 12
THEN 31
END AS 'No of Days in the month'

Solution 4
SELECT DAY(DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@d),@d)))) AS '
No of Days in the month
'

No comments:

Post a Comment