Please disable your adblock and script blockers to view this page
 

Sql Query to Get First, Last Date and Total Days in Year or Month

Introduction: In this article I am going to share how to find first and last day of the year or month and count the total number of days in year or month from the current or any date in Sql Server.


Description: Many times we need to get the first and last day of the month or year and also count of total days in month or year for many purposes. Here I have mentioned the query to get the starting and end date of the month or year and count of total days.

Implementation: Let write the queries to get the desired results

Get First, Last Date and Total Days in Year

DECLARE @MyDate DATE=GETDATE(), @FirstDate DATE,@LastDate DATE, @TotalDays INT

SET @FirstDate=(SELECT DATEADD(DAY,-(DATEPART(DAYOFYEAR,@MyDate))+1,@MyDate))
SET @LastDate= (SELECT DATEADD(DAY,-(DATEPART(DAYOFYEAR,DATEADD(YEAR,1,@MyDate))),DATEADD(YEAR,1,@MyDate)))
SET @TotalDays=(DATEDIFF(D,@FirstDate,@LastDate))+1

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

Output: 
First Date of Year
Last Date of Year
Total Days in Year
2016-01-01
2016-12-31
366

Get First, Last Date and Total Days in Month

DECLARE @MyDate DATE=GETDATE(), @FirstDate DATE,@LastDate DATE, @TotalDays INT

SET @FirstDate=(SELECT DATEADD(DAY ,-(DAY(@MyDate )-1),@MyDate ))
SET @LastDate=(SELECT  DATEADD(DAY ,-(DAY(@MyDate )), DATEADD(MONTH,1,@MyDate )))
SET @TotalDays=(DATEDIFF(D,@FirstDate,@LastDate))+1

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

Output: 
First Date of Month
Last Date of Month
Total Days in Month
2016-05-01
2016-05-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.. ConversionConversion EmoticonEmoticon