How to find last day of previous ,current and next month using sql server?

How to find last day of previous ,current and next month using sql server?

Following Query demonstrates the script to find last day of previous, current and next month.

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))

OutPut:-
2010-03-31 23:59:59.000
SELECT convert(varchar(10),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))
OutPut:-
Mar 31 201


----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
OutPut:-
2010-04-30 23:59:59.000

SELECT convert(varchar(10),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)))
OutPut:-
Apr 30 201


----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
OutPut:-
2010-05-31 23:59:59.000
SELECT convert(varchar(10),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)))
OutPut:-
May 31 201

If you want to find last day of month of any day specified use following Query.
--Last Day of Any Month and Year
DECLARE @dtDate DATETIME
SET @dtDate = '8/18/2003'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))

No comments:

Post a Comment

Plz Share your comments...