Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

How to find the first and last days in years, months etc

From Wiki

Jump to: navigation, search

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

  1. DECLARE @d datetime
  2. SET @d = '20071010'
  3.  
  4. SELECT
  5.     DATEADD(yy, DATEDIFF(yy, 0, @d), 0) as FirstDayOfYear,
  6.     DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) as LastDayOfYear,
  7.     DATEADD(qq, DATEDIFF(qq, 0, @d), 0) as FirstDayOfQuarter,
  8.     DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) as LastDayOfQuarter,
  9.     DATEADD(mm, DATEDIFF(mm, 0, @d), 0) as FirstDayOfMonth,
  10.     DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) as LastDayOfMonth,
  11.     @d - DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7 AS FirstDayOfWeek,
  12.     @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:

  1. DECLARE @d DATE
  2. SET @d = GETDATE()
  3.  
  4. SELECT
  5.     DATEADD(yy, DATEDIFF(yy, 0, @d), 0) AS FirstDayOfYear,
  6.     DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) AS LastDayOfYear,
  7.     DATEADD(qq, DATEDIFF(qq, 0, @d), 0) AS FirstDayOfQuarter,
  8.     DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) AS LastDayOfQuarter,
  9.     DATEADD(mm, DATEDIFF(mm, 0, @d), 0) AS FirstDayOfMonth,
  10.     DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) AS LastDayOfMonth,
  11.     dateadd(day,- DATEDIFF(dd, @@DATEFIRST - 1, @d) % 7,@d) AS FirstDayOfWeek,
  12.     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

83 Rating: 3.8/5 (47 votes cast)