Find First and Last Day Of Each Month

The first day of each month is always 1. However if you interested to find the First and Last Date of each month using a T-Sql Query, here it is:

-- Return First and Last Date of a Month
DECLARE @Month smallint
SET @Month = 1

SELECT DAY(DATEADD(Month, DATEDIFF(Month, -1, getdate()) - 2, -1) + 1) as FirstDayofMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

If you wish to find out the Lastday of the previous month, just set @Month to 0.

Note: The value for @Month depends on the current month you are in. So if this month is September, the value of @Month is 1. Similarly for Oct(2), Nov(3), Dec(4), Jan(5), Feb(6) and so on.

Also read SQL Server: First and Last Sunday of Each Month


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

5 comments:

Dh@v@! said...

Thanks for your tips...

I want to find out First day of each week for weekly report purpose, could you help in finding that?

தமிழ்நெஞ்சம் said...

For February your code is giving 31 days. please check it.

Suprotim Agarwal said...

Hi,

The query works fine. The value for @Month depends on the current month you are in. So if this month is September, the value of @Month is 1. Similarly for Oct(2), Nov(3), Dec(4), Jan(5), Feb(6) and so on..

I have added a note to avoid confusion. Apologies if that wasn't clear earlier.

Pimenta said...

Thanks for the code, it really helped me. Just what I needed.

Anonymous said...

Thank you, this helped me.