How to get first and last day of previous month (with timestamp) in SQL Server

Jay S picture Jay S · Jul 31, 2012 · Viewed 494.4k times · Source

I could not find the solution which gives first and last day of previous month with timestamp. Hope this helps others. If there is already a solution for this problem I apologize.

Here is the solution.

 SELECT DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0) as FirtDayPreviousMonthWithTimeStamp,
    DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as LastDayPreviousMonthWithTimeStamp

This will return the following if currentdate = '2012-7-31'

result: 2012-06-01 00:00:00.000 2012-06-30 23:59:59.000

This will return the following if currentdate = '2012-1-1'

result: 2011-12-01 00:00:00.000 2011-12-31 23:59:59.000

Answer

AnandPhadke picture AnandPhadke · Jul 31, 2012
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month