Another Number of Days in Month Function

,

Here is another Number of Days in the Month function for SQL Server without the use of Case or if statements. It uses the DATEPART and DATEADD built-in functions.

CREATE function fDaysInMonth (@dtIn datetime)
returns int
as
begin
/*
For SQL Server
Description:
   Function designed to calculate the number days in a month.
*/

	DECLARE @strDayOne as CHAR(20)

	--Get the first day of the month of the date passed.
	SET @strDayOne = CAST(DATEPART(yyyy,@dtIn) AS CHAR(4)) + '-' + CAST(DATEPART(mm,@dtIn) AS CHAR(2)) + '-01'

	--Return one month forward less one day then extract the last day of the month as number of days.
	RETURN DATEPART(dd,DATEADD(m,1,@strDayOne)-1)

end

Rate

Share

Share

Rate