Monday, March 26, 2012

SQL SERVER – Find First Day / Last Day of any month - Current - Previous - Next



Use the below queries as a sample to find the First day and Last Day of any month.
The sample below shows the First and Last days for previous and next months.


DECLARE @today DATETIME
SELECT @today = GETDATE();
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)),@today),101) ,
'Last Day of Previous Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)-1),@today),101) AS Date_Value,
'First Day of Current Month' AS Date_Type
UNION ALL
SELECT CONVERT(VARCHAR(25),@today,101) AS Date_Value, 'Today' AS Date_Type
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))),DATEADD(mm,1,@today)),101) ,
'Last Day of Current Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))-1),DATEADD(mm,1,@today)),101) ,
'First Day of Next Month'
UNION ALL
SELECT CONVERT(VARCHAR(25),DATEADD(dd,1-day((DATEADD(mm,-1,@today))),DATEADD(mm,-1,@today)),101) AS Date_Value,
'First Day of Previous Month' AS Date_Type

Alternatively you can also use the below code, this gives time precision also:

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth


No comments:

Post a Comment