From the DATEADD documentation:
If datepart is month and the date month has more days than the return month and the date day does not exist in the return month, the last day of the return month is returned. For example, September has 30 days; therefore, the two following statements return 2006-09-30 00:00:00.000:
SELECT DATEADD(month, 1, '2006-08-30');
SELECT DATEADD(month, 1, '2006-08-31');
The SQL Server
knows that the last day of 2016-03
is 31
and the last day of the 2016-04
is 30
:
SELECT DAY(EOMONTH('2016-03-01')) -- 31
SELECT DAY(EOMONTH('2016-04-01')) -- 30
Then why the following:
SELECT DATEADD(MONTH, -1, '2016-04-30')
returns 2016-03-30 00:00:00.000
instead 2016-03-31 00:00:00.000
?
Also, if I have the following:
SELECT DATEADD(MONTH, -1, '2016-03-31')
it correctly returns 2016-02-29 00:00:00.000
.
SELECT DATEADD(MM, DATEDIFF(MM, -1, GETDATE()), 0) - 1 LastDayOfMonth
– pastacool<
rather than<=
) – Damien_The_Unbeliever