SQL SERVER: Pass Month and Year value and get First, Last and Total Days in that month

Introduction: In this article I am going to share how to find first and last day of the month and also count total number of days in the month from the month and year value.


Description: While working on Asp.Net project with Sql Sever as a backend it was required to pass month value (e.g. 3) and year value (e.g. 2016) and get the first and last date and total days in that month. Here I have mentioned the query to get the desired result.

Implementation: Let’s write sample query for demonstration purpose:


DECLARE @Month INT=3, @Year INT=2016, @FirstDate DATE,@LastDate DATE, @TotalDays INT

SET @LastDate=(SELECT DATEADD(DAY,-1,DATEADD(MONTH,@Month,DATEADD(YEAR,@Year-1900,0))))
SET @FirstDate=(SELECT DATEADD(MONTH,@Month-1,DATEADD(YEAR,@Year-1900,0)))

SET @TotalDays=(DATEDIFF(D,@FirstDate,@LastDate))+1

SELECT @FirstDate [First Date of Month] ,@LastDate [Last Date of Month], @TotalDays [Total Days in Month]

Result:
First Day of Month
Last Day of Month
Total Days in Month
2016-03-01
2016-03-31
31

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..