I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:
DATEADD(DAY, DATEADD(MONT
Works in SQL server
Declare @GivenDate datetime
SET @GivenDate = GETDATE()
Select DATEADD(MM,DATEDIFF(MM, 0, @GivenDate),0) --First day of the month
Select DATEADD(MM,DATEDIFF(MM, -1, @GivenDate),-1) --Last day of the month
Just extend your formula out a little bit:
dateadd(day, -1,
dateadd(month, 1,
cast(month('5/15/2009') as varchar(2)) +
'/1/' +
cast(year('5/15/2009') as varchar(4)))
WinSQL to get last day of last month (i.e today is 2017-02-09, returns 2017-01-31: Select dateadd(day,-day(today()),today())
I wrote following function, it works.
It returns datetime data type. Zero hour, minute, second, miliseconds.
CREATE Function [dbo].[fn_GetLastDate]
(
@date datetime
)
returns datetime
as
begin
declare @result datetime
select @result = CHOOSE(month(@date),
DATEADD(DAY, 31 -day(@date), @date),
IIF(YEAR(@date) % 4 = 0, DATEADD(DAY, 29 -day(@date), @date), DATEADD(DAY, 28 -day(@date), @date)),
DATEADD(DAY, 31 -day(@date), @date) ,
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date))
return convert(date, @result)
end
It's very easy to use. 2 example:
select [dbo].[fn_GetLastDate]('2016-02-03 12:34:12')
select [dbo].[fn_GetLastDate](GETDATE())
Here's my version. No string manipulation or casting required, just one call each to the DATEADD
, YEAR
and MONTH
functions:
DECLARE @test DATETIME
SET @test = GETDATE() -- or any other date
SELECT DATEADD(month, ((YEAR(@test) - 1900) * 12) + MONTH(@test), -1)
I know this is a old question but here is another solution that works for me
SET @dtDate = "your date"
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
And if some one is looking for different examples here is a link http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
I hope this helps some one else. stackoverflow Rocks!!!!