How to get number of days from month and year

Ashish Batra picture Ashish Batra · Jun 26, 2013 · Viewed 13.3k times · Source

I want to get the number of days in the month which the user specifies. I am using this it works for most months except for Feb and leap year. It shows 28 days and not 29. Can you solve this?

begin
declare @year int
declare @month int
select @year = 2012
select @month = DATEPART(mm,CAST('August'+ ' 2012' AS DATETIME))
select  datediff(day, 
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month - 1, 0)),
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month, 0))) as number_of_days

end

Or If not can you tell me another approach to do this. It should use @year and @month and the code to find the days can be any!

Answer

GarethD picture GarethD · Jun 26, 2013

If you need to do this from year and month (assuming both are integers) you could create a function as so:

CREATE FUNCTION dbo.DaysInMonth (@year INT, @Month INT)
RETURNS INT 
AS
BEGIN
    -- FIRST CONVERT THE YEAR AND MONTH TO A DATE BY CASTING TO CHAR
    -- THEN CONCATENATING TO CREATE A STRING IN THE FORMAT yyyyMMdd
    -- THIS DATEFORMAT IS CULTURE INSENSITIVE SO WILL WORK NO MATTER
    -- WHAT YOUR REGIONAL SETTINGS ARE

    DECLARE @Date DATE = CAST(
                            CAST(@Year AS CHAR(4)) 
                            + RIGHT('0' + CAST(@Month AS VARCHAR(2)), 2)
                            + '01' AS DATE);

    -- USE ESTABLISHED METHODS OF GETTING 1ST OF THE MONTH AND FIRST OF 
    -- THE NEXT MONTH AND CALCULATE THE DIFFERENCE
    RETURN DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0));
END
GO
-- TEST FUNCTION
SELECT  DaysInMonth = dbo.DaysInMonth(2012, 2);

Example on SQL Fiddle