Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

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


Contributed By: --SQLDenis 16:41, 30 May 2008 (GMT)


Part of SQL Server Programming Hacks

Section Dates

83 Rating: 2.6/5 (7 votes cast)