15

I want to get the last day( Sunday) of current week given any timestamp. I tried following script, but it returns Saturday as the last day rather than Sunday as I expected.

Select DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()) AS 'Last Day Of Week' 

Any answer is welcomed!!

Echo
  • 1,117
  • 4
  • 22
  • 43

4 Answers4

20

It will work if you change the standard DATEFIRST from Sunday (7) to Monday (1):

SET DATEFIRST 1

Select DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()) AS 'Last Day Of Week' 
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
2
DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 6)

I know this post is old but this post comes at the top when searched through via Google.

Always good to be updating.

Jona
  • 327
  • 4
  • 19
1

The below doesn't work on a sunday with some DATEFIRST (languages):

    DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 6)

Also, setting DATEFIRST is not always an option (functions can't use SET DATEFIRST)

Here's one that's universal:

  • It's geared for weeks starting on a Monday
  • Always returns the Sunday of the current week
  • Works regardless of the DATEFIRST setting
  • Does not change DATEFIRST so can be used in a function
    DECLARE @today DATE = getdate(); (or any other date);

    SELECT dateadd(day, ((15-@@datefirst) - datepart(dw, @today)) % 7, @today);
Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
0

Prefix your command with set datefirst 1

podiluska
  • 50,950
  • 7
  • 98
  • 104