Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
How to find the first and last days in years, months etc
From Wiki
This example will return the first and last day for the year, quarter, month and week for any date passed in.
The example date is October 10th 2007, change that to any date you want
- DECLARE @d datetime
- SET @d = '20071010'
- SELECT
- DATEADD(yy, DATEDIFF(yy, 0, @d), 0) as FirstDayOfYear,
- DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) as LastDayOfYear,
- DATEADD(qq, DATEDIFF(qq, 0, @d), 0) as FirstDayOfQuarter,
- DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) as LastDayOfQuarter,
- DATEADD(mm, DATEDIFF(mm, 0, @d), 0) as FirstDayOfMonth,
- DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) as LastDayOfMonth,
- @d - DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7 AS FirstDayOfWeek,
- @d - DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7 + 6 AS LastDayOfWeek
and here is a version that avoids date clash problem if you're using new date type in SQL Server 2008:
- DECLARE @d DATE
- SET @d = GETDATE()
- SELECT
- DATEADD(yy, DATEDIFF(yy, 0, @d), 0) AS FirstDayOfYear,
- DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) AS LastDayOfYear,
- DATEADD(qq, DATEDIFF(qq, 0, @d), 0) AS FirstDayOfQuarter,
- DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) AS LastDayOfQuarter,
- DATEADD(mm, DATEDIFF(mm, 0, @d), 0) AS FirstDayOfMonth,
- DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) AS LastDayOfMonth,
- dateadd(day,- DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7,@d) AS FirstDayOfWeek,
- dateadd(day, - DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7 + 6, @d) AS LastDayOfWeek
Contributed By: --SQLDenis 16:41, 30 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Dates



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.