Technical Article

Finding first/last day of month by a date

,

This script finds the first day of previous, current and next month as well as last day of previous, current and next month.

The calculation is based on the ISO date format which makes it independant of the date format used on the SQL Server.

The calculation is performed from a date - it can be altered to use a year/month combination

declare @SomeDate datetime
set @SomeDate = getdate()

select   convert( datetime,
replace(str(year(dateadd("m", -1, @SomeDate)), 4), ' ', '0') + replace(str(month(dateadd("m", -1, @SomeDate)), 2), ' ', '0') + '01',
112) as FirstDayPrevMonth,
            convert(datetime,
replace(str(year(@SomeDate), 4), ' ', '0') + replace(str(month(@SomeDate), 2), ' ', '0') + '01',
112) as FirstDayThisMonth,
            convert( datetime,
replace(str(year(dateadd("m", 1, @SomeDate)), 4), ' ', '0') + replace(str(month(dateadd("m", 1, @SomeDate)), 2), ' ', '0') + '01',
112) as FirstDayNextMonth,
            convert( datetime,
replace(str(year(@SomeDate), 4), ' ', '0') + replace(str(month(@SomeDate), 2), ' ', '0') + '01',
112)-1 as LastDayPrevMonth,
            convert( datetime,
replace(str(year(dateadd("m", 1, @SomeDate)), 4), ' ', '0') + replace(str(month(dateadd("m", 1, @SomeDate)), 2), ' ', '0') + '01',
112)-1 as LastDayThisMonth,
            convert( datetime,
replace(str(year(dateadd("m", 2, @SomeDate)), 4), ' ', '0') + replace(str(month(dateadd("m", 2, @SomeDate)), 2), ' ', '0') + '01',
112)-1 as LastDayNextMonth

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating