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

Viewed 632754

I could not find the solution which gives first and last day of previous month with timestamp.

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

12 Answers

To get last month's first date:

select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) LastMonthFirstDate                                                                

To get last month's last date:

select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) LastMonthEndDate
Related