Phattharawit Sombatrat Phattharawit Sombatrat - 4 months ago 14
SQL Question

How to get last date of month SQL Server 2008

I created a function "ufngetFirstDateOfMonth" and "ufngetLastDateOfMonth" stored in Microsoft SQL Server 2008. My purpose is to send some date into the function and it will return the first date of month with '00:00:00' or the last date of month with '23:59:59'.

I call the function like this:

exec ufngetLastDateOfMonth('2014-10-15')

and normally it returns '2014-10-31 23:59:59'

but when I send the last date of months that have 31 days (august, january,...):

exec ufngetLastDateOfMonth('2014-10-31')

it return '2014-10-30 23:59:59' whick is not correct Actally, it should be '2014-10-31 23:59:59'

Something goes wrong here...

This is my function:

CREATE FUNCTION [dbo].[ufnLastDateOfMonth](@Date date)
RETURNS varchar(50)


DECLARE @New_Date varchar(50)

select @New_date = cast(dateadd(dd,-(DAY(@Date )),DATEADD(mm,1,@Date ))as varchar(50)) + ' 23:59:59'

RETURN @New_Date



To get the last day you can do this:

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,'2014-08-12')+1,0))

Adding to your function:

select @New_date = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@date)+1,0))


SQL SERVER – Find Last Day of Any Month – Current Previous Next