In SQL Server, this is how I usually get to the last day of the month regarding an arbitrary point in time:
select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
In a nutshell:
- From your point of reference
- Add 1 month,
- Then subtract its day of the week in days from the obtained value.
Voila! You have the last day of the month containing your checkpoint in time.
Getting the first day of the month is easier:
select dateadd(day,-(day(current_timestamp)-1),current_timestamp)
- From your point of reference
- subtract (in days), 1 less than the current component of the day of the month.
Disabling / normalizing the extraneous component remains as an exercise for the reader.
source share