Wednesday, October 6, 2010

First and Last day of a month.

To find First and last days of the month..

here I use the DATEDIFF function with m datepart and 0 which is for '1900-01-01'

First day of the month

For previous month
SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)

For current month
SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)

For next month
SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)

Last day of the month
Here in this I have used the same code to compute First day of a month ,but after that I have added the result with by -1 second..
So when a date has 12.00 Am today then -1 second of it 11.59 Pm of the previous day.
this is how it has been done..

For previous month
select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))

For current month
select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))

For next month
select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))