DECLARE @entry_date DATETIME ,@start_date DATETIME ,@end_date DATETIME SET @entry_date = '7-1-2013' -- Set Start Date to first day of the month for given date SET @start_date = ( SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(@entry_date) - 1), @entry_date), 101) ) -- Set End Date to last day of the month for given date SET @end_date = ( SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(DATEADD(mm, 1, @entry_date))), DATEADD(mm, 1, @entry_date)), 101) )
----Last Day of Previous Month SELECT DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0)) LastDay_PreviousMonth ----Last Day of Current Month SELECT DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) LastDay_CurrentMonth ----Last Day of Next Month SELECT DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 2, 0)) LastDay_NextMonth --Last Day of Any Month and Year DECLARE @dtDate DATETIME SET @dtDate = '8/18/2007' SELECT DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, @dtDate) + 1, 0)) LastDay_AnyMonth
LastDay_PreviousMonth ----------------------- 2013-07-31 23:59:59.000 LastDay_CurrentMonth ----------------------- 2013-08-31 23:59:59.000 LastDay_NextMonth ----------------------- 2013-09-30 23:59:59.000 LastDay_AnyMonth ----------------------- 2007-08-31 23:59:59.000
DECLARE @mydate DATETIME SELECT @mydate = GETDATE() SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(@mydate)), @mydate), 101) ,'Last Day of Previous Month' UNION SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(@mydate) - 1), @mydate), 101) AS Date_Value ,'First Day of Current Month' AS Date_Type UNION SELECT CONVERT(VARCHAR(25), @mydate, 101) AS Date_Value ,'Today' AS Date_Type UNION SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(DATEADD(mm, 1, @mydate))), DATEADD(mm, 1, @mydate)), 101) ,'Last Day of Current Month' UNION SELECT CONVERT(VARCHAR(25), DATEADD(dd, - (DAY(DATEADD(mm, 1, @mydate)) - 1), DATEADD(mm, 1, @mydate)), 101) ,'First Day of Next Month' GO
07/31/2013 Last Day of Previous Month 08/01/2013 First Day of Current Month 08/07/2013 Today 08/31/2013 Last Day of Current Month 09/01/2013 First Day of Next Month
Source:
- http://blog.sqlauthority.com/2007/05/13/sql-server-query-to-find-first-and-last-day-of-current-month/
- http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
Last Updated on October 26, 2015