Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous Monday & previous Sunday's date based on today's date

Tags:

sql

tsql

I need the correct syntax to give me :

  1. Previous week's Monday's date based on the current date/time using GETDATE()
  2. Previous week's Sunday's date based on the current date/time using GETDATE()

So, based on today's date (14/09/2012) I would want the following:

  1. Previous Monday's date = 03/09/2012
  2. Previous Sunday's date = 09/09/2012
like image 979
JsonStatham Avatar asked Sep 14 '12 09:09

JsonStatham


People also ask

How do I find previous Monday dates?

To get the date of the previous Monday: Add 6 to the day of the week and get the remainder of dividing by 7 . Subtract the result from the day of the month.

How do I get previous Monday dates in Excel?

=A2-WEEKDAY(A2-2) Get First Monday Before Any Date in Excel. The Excel WORKDAY Function automatically returned 5)12/1980 as the first Monday occuring before the date in cell A2.


1 Answers

Easy:

--start of last week SELECT DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0)  --end of last week SELECT DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 6) 

EDIT:

The below will handle the Sunday date issue.

DECLARE @input varchar(10) --SET @input = '9/9/2012' -- simulates a Sunday SET @input = GETDATE()  --start of last week SELECT DATEADD(wk, DATEDIFF(wk, 6,  CASE DATEPART(dw,@input) WHEN 1 THEN DATEADD(d,-1,@input) ELSE @input END ), 0)  --end of last week SELECT DATEADD(wk, DATEDIFF(wk, 6,  CASE DATEPART(dw,@input) WHEN 1 THEN DATEADD(d,-1,@input) ELSE @input END ), 6) 
like image 84
general exception Avatar answered Sep 30 '22 09:09

general exception