How to get First and Last Date of Current Month using Sql Server 2005?

How to get First and Last Date of Current Month using Sql Server 2005?

Here is the sample code to do it.

declare @startDate datetime
declare @EndDate datetime
declare @currentDate datetime
set @currentDate = getdate()

set @startDate = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@currentDate)-1),@currentDate),101) -- 1st day of current month
set @EndDate = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@currentDate))),DATEADD(mm,1,@currentDate)),101) -- last day of current month

declare @startDateTwoYearsBack datetime
set @startDateTwoYearsBack = DATEADD(yy,-2,@startDate) -- for getting date which is 2 years back.

print @StartDate -- Sep 1 2008 12:00AM -- First Date of Current Month
print @EndDate -- Sep 30 2008 12:00AM -- Last Date of Current Month
print @startDateTwoYearsBack -- Sep 1 2006 12:00AM

No comments: