Click here to Skip to main content
15,898,588 members
Articles / DevOps
Tip/Trick

Computing First and Last Day of Current and Previous Month (SQL Server)

Rate me:
Please Sign up or sign in to vote.
2.40/5 (3 votes)
26 Sep 2017CPOL2 min read 22.7K   51   5   13
A quick way to calculate first and last day of curent month and previous month

Introduction

This tip is about getting first and last day of current and previous month, a highly desired requirement in many database and reporting solutions.

There are many examples available but it is always good to explore them further.

SQL2008R2 and previous versions require work around to calculate first and last day of the month. It is very important to keep a consistent approach to calculate the first and last day of the current and previous month.

Despite the fact that SQL2012 and upward versions provide built in EOMONTH() function to calculate first day and last day of month, it is worth considering to understand how to get there without the need to use EOMONTH() because the code can be modified further for related computations.

Logic Behind Code

If you know the logic behind the code, it is relatively easier to understand and write the code.

Get First Day of Current Month

  1. Subtract all days of the current month
  2. Add one day to get first day

Get Last Day of Current Month

  1. Get (same) current day of next month
  2. Subtract all the days of next month

Get First Day of Previous Month

  1. Get previous month
  2. Subtract all days of the previous month
  3. Add one day to get first day

Get Last Day of Previous Month

Subtract all the days of current month

Coding Example

The workaround is to use DateAdd() function to subtract days of month using Day() function according to the requirements as shown below in the coding example:

SQL
--=================================================================================================
-- (1) Get first day of current month
--=================================================================================================
-- Subtract all days of current month
DECLARE @MonthFirstDay DATETIME =_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-DAY(GETDATE()),GETDATE()),106))
 
-- Add one day to get first day
SET @MonthFirstDay=@MonthFirstDay+1
 
-- Show first day of current month
SELECT @MonthFirstDay as MonthFirstDay
--================================================================================================
-- (2) Get last day of current month
--================================================================================================
-- Get (same) current day of next month
DECLARE @MonthLastDay DATETIME=(SELECT CONVERT(CHAR(15),DATEADD(MM,1,GETDATE()),106))
 
-- Subtract all the days of next month
SET @MonthLastDay=DATEADD(DD,-DAY(@MonthLastDay),@MonthLastDay)
 
-- show last day of current month
SELECT @MonthLastDay as MonthLastDay
 
--=================================================================================================
-- (3) Get first day of previous month
--=================================================================================================
-- Get previous month
DECLARE @PrevMonthFirstDay DATETIME =(SELECT CONVERT(CHAR(15),DATEADD(MM,-1,GETDATE()),106))
 
-- Subtract all days of previous month
SET @PrevMonthFirstDay=_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-DAY(@PrevMonthFirstDay),@PrevMonthFirstDay),106))
 
-- Add one day to get first day
SET @PrevMonthFirstDay=@PrevMonthFirstDay+1
 
-- Show first day of previous month
SELECT @PrevMonthFirstDay as PrevMonthFirstDay
 
--=================================================================================================
-- (2) Get last day of previous month
--=================================================================================================
-- Subtract all the days of current month
DECLARE @PrevMonthLastDay DATETIME=_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-Day(GETDATE()),GETDATE()),106))
 
-- show last day of current month
SELECT @PrevMonthLastDay as PrevMonthLastDay

Image 1

Points of Interest

It is recommended to convert these scripts into procedures to avoid repetition of the code and then relying on calling the stored procedures whenever required.

Think of a transactional monthly report where you cannot use built-in function EOMonth() due to version limitation then it is handy to pre-calculate beginning and end of the current month using the above scripts (better if turned into procedures).

References

  1. http://blog.sqlauthority.com/2007/05/13/sql-server-query-to-find-first-and-last-day-of-current-month/
  2. https://sqlmate.wordpress.com/2012/08/24/get-first-and-last-day-of-month-in-sql-2012-and-sql-2008-and-earlier/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Database Developer
United Kingdom United Kingdom
Haroon's deep interest in logic and reasoning at an early age of his academic career paved his path to become a data professional.

He began his professional life as a computer programmer more than 10 years ago working on his first data venture to migrate and rewrite a public sector database driven examination system from IBM AS400 (DB2) to SQL Server 2000 using VB 6.0 and Classic ASP along with developing reports and archiving many years of data.

His work and interest revolves around Database-Centric Architectures and his expertise include database and reports design, development, testing, implementation and migration along with Database Life Cycle Management (DLM).

Comments and Discussions

 
GeneralMy vote of 3 Pin
Zeleax27-Sep-17 22:33
Zeleax27-Sep-17 22:33 
QuestionEOMONTH Pin
Zeleax27-Sep-17 19:18
Zeleax27-Sep-17 19:18 
AnswerRe: EOMONTH Pin
Haroon Ashraf27-Sep-17 21:59
Haroon Ashraf27-Sep-17 21:59 
QuestionProblems with data type and basic assumptions... Pin
SqlNightOwl27-Sep-17 11:26
professionalSqlNightOwl27-Sep-17 11:26 
AnswerRe: Problems with data type and basic assumptions... Pin
Haroon Ashraf28-Sep-17 1:36
Haroon Ashraf28-Sep-17 1:36 
GeneralRe: Problems with data type and basic assumptions... Pin
SqlNightOwl28-Sep-17 3:32
professionalSqlNightOwl28-Sep-17 3:32 
GeneralRe: Problems with data type and basic assumptions... Pin
Haroon Ashraf28-Sep-17 5:28
Haroon Ashraf28-Sep-17 5:28 
SuggestionWhy not just use the first date of the current month as seed? Pin
Komron Nouri26-Sep-17 9:48
Komron Nouri26-Sep-17 9:48 
GeneralRe: Why not just use the first date of the current month as seed? Pin
Haroon Ashraf26-Sep-17 11:25
Haroon Ashraf26-Sep-17 11:25 
Thanks for sharing your code and feedback.

Now I would like to share some more background about this tip.

This tip was written keeping four things in mind:

1. First of all this is a tip for the beginners (not for experts like you Smile | :) )
2. Secondly this was shared keeping in mind that four different but independent functions can replace these scripts to avoid coding repetition so seed cannot be used as in your case the code always rely on calculating the first day of current month and then referring to it afterwards (nevertheless it is an excellent solution)
3. Thirdly this script was instantly written the time it was required and worked very fine despite the fact I knew far more better solutions are there (but it is nice to share your work just like you shared with us)
4. The purpose was to walk through the steps involved to build all these methods starting from the basics so this is rather simpler than using CTE or derived table (plus you might have noticed that I have not used any other string function like concat).

The next revision of the article (soon) is going to be focussed on constructing the method from the very basic step as mentioned above plus I am also considering to add your precious code portion (with your permission) to give alternative approach.

Thank you very much for your time and effort.Thumbs Up | :thumbsup:
GeneralRe: Why not just use the first date of the current month as seed? Pin
Komron Nouri26-Sep-17 12:04
Komron Nouri26-Sep-17 12:04 
GeneralRe: Why not just use the first date of the current month as seed? Pin
Haroon Ashraf26-Sep-17 21:44
Haroon Ashraf26-Sep-17 21:44 
QuestionThis is what I use to find the last day of a month Pin
#realJSOP26-Sep-17 8:25
professional#realJSOP26-Sep-17 8:25 
AnswerRe: This is what I use to find the last day of a month Pin
Haroon Ashraf26-Sep-17 11:33
Haroon Ashraf26-Sep-17 11:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.