Login or Sign Up to become a member!
LessThanDot Sit 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 friendfeed 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

Getting the First and last days of month, quarter and week

From Wiki

Jump to: navigation, search

By using dateadd and datediff together you can get the first and last day for years, quarters, months and weeks(be careful of ISO weeks!) Run the code below to see how this works

  1. DECLARE @d DATETIME
  2.     SET @d = '20071010'
  3.  
  4.     SELECT DATEADD(yy, DATEDIFF(yy, 0, @d), 0) AS FirstDayOfYear,
  5.     DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) AS LastDayOfYear,
  6.     DATEADD(qq, DATEDIFF(qq, 0, @d), 0) AS FirstDayOfQuarter,
  7.     DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) AS LastDayOfQuarter,
  8.     DATEADD(mm, DATEDIFF(mm, 0, @d), 0) AS FirstDayOfMonth,
  9.     DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) AS LastDayOfMonth,
  10.     DATEADD(wk, DATEDIFF(wk, 0, @d), 0) AS FirstDayOfWeek,
  11.     DATEADD(wk, DATEDIFF(wk, 0, @d)+1, -1) AS LastDayOfWeek


Change the value of the @d variable to test with other dates

Contributed by: SQLDenis

120 Rating: 1.5/5 (4 votes cast)