First day of next month: Get the first day of the current month and add 1 month?
These kinds of functions are used in procedure/ reports, SSIS ETLS to extract the data based on the dates. Below are the functions with logic explanation:
1. First day of current month:
select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0):
in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.
2. Last day of current month:
SELECT cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) as date):starting from innermost query(DATEDIFF(m,0,GETDATE()))
will help you to take out the difference between the months from 0 to current date after that we will add a month to it which will make it next month after that we will subtract 1 sec from it and which will give us the last second of this month post that we will cast that into date, to get last day of this month.
3. First day of next month:
SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0) ):
in this we have taken out the difference between the months from 0 to current date and then add 1 to the difference and 0 this will return the first day of next month.
In the similar logic we can extract:
4. Last day of next month:
SELECT cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) as date)
5. First day of previous month:
select DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)
6. Last day of previous month:
SELECT cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) as date)
7. First day of current year:
Select DATEADD(yy, DATEDIFF(yy,0,GETDATE()),0): in this case we will extract the difference between the years and add
8. Last day of current year:
SELECT cast(DATEADD(s,-1,DATEADD(yy, DATEDIFF(yy,0,GETDATE()),0)) as date)