Skip to content

Instantly share code, notes, and snippets.

@bilalhusain
Created March 2, 2012 12:12
Show Gist options
  • Save bilalhusain/1958059 to your computer and use it in GitHub Desktop.
Save bilalhusain/1958059 to your computer and use it in GitHub Desktop.
tsql, last week start and end date
-- fetches the last week date range (sunday to sunday)
-- for the specified time zone offset
DECLARE @OffsetMinutes AS SMALLINT = +330
DECLARE @UtcDate AS DATETIME = GETUTCDATE()
DECLARE @LocalDate AS DATETIME = DATEADD(MINUTE, @OffsetMinutes, @UTCDATE)
DECLARE @LastSunday AS DATETIME = CONVERT(VARCHAR(4), YEAR(@LocalDate))
+ '-' + CONVERT(VARCHAR(2), MONTH(@LocalDate))
+ '-' + CONVERT(VARCHAR(2), DAY(@LocalDate))
WHILE (DATENAME(WEEKDAY, @LastSunday) <> 'Sunday')
SET @LastSunday = DATEADD(DAY, -1, @LastSunday)
DECLARE @StartDate AS DATETIME = DATEADD(DAY, -7, @LastSunday)
DECLARE @EndDate AS DATETIME = DATEADD(DAY, 7, @StartDate) -- the code is intentional to highlight the range of 7 days
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment