Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the start day (Monday) of the current week

Looking for a SQL query/queries that would determine the start day (Monday) of the current week.

Example: If today is -> then the start of the week is

Sat Oct 09, 2010 -> Start of the week is Monday Oct 04, 2010
Sun Oct 10, 2010 -> Start of the week is Monday Oct 04, 2010
Mon Oct 11, 2010 -> Start of the week is Monday Oct 11, 2010
Tue Oct 12, 2010 -> Start of the week is Monday Oct 11, 2010

I have seen many "solutions" on Google and StackOverflow. The look something like:

SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111)
SELECT DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate)

This fails because: Sun Oct 10, 2010 -> start of week Monday Oct 11, 2010 (which is incorrect).

like image 586
del.ave Avatar asked Oct 14 '10 19:10

del.ave


3 Answers

Try using DATEFIRST to explicitly set the day of week to be regarded as the 'first'.

set DATEFIRST 1  --Monday
select DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate)

This will return the Monday of the week the InputDate falls in.

like image 159
p.campbell Avatar answered Nov 13 '22 10:11

p.campbell


Building on top of p.campbell's solution, if you don't want to use or can't use "SET DATEFIRST 1", you can get around that by doing the following:

SELECT DATEADD(DD, 2 - DATEPART(DW, DATEADD(DD, -1, @pInputDate)), DATEADD(DD, -1, @pInputDate))
like image 22
Jay Horita Avatar answered Nov 13 '22 08:11

Jay Horita


The most simple implementation

SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) MondayOfCurrentWeek

like image 34
N. Haut Avatar answered Nov 13 '22 09:11

N. Haut