Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# First and Last day of the week in any given Date

Posted on 2006-07-15
Medium Priority
271 Views
I want to get the first and the last day of the week by giving any date, in my case our first day start from saturday.

for example if i give 18/07/2006 it should return 15 for the first day of the week and 21 as the last day of the week.

Kind regards,
0
Question by:altuwairqi2
• 4
• 2

LVL 75

Expert Comment

ID: 17114506
Something like this:

Declare      @Dat datetime
Set @Dat = '2006-07-18'

Declare @DateFirst tinyint

Set @DateFirst = @@DATEFIRST    -- Save old @@DATEFIRST value
SET DATEFIRST 6

Select      DATEADD(day, -DATEPART(weekday, @Dat) + 1, @Dat) FirstDayOfWeek,
DATEADD(day, 7 - DATEPART(weekday, @Dat), @Dat) LastDayOfWeek
SET DATEFIRST @DateFirst

Select @@DATEFIRST    -- Restore old @@DATEFIRST value
0

LVL 75

Expert Comment

ID: 17114521

Declare      @Dat datetime
Set @Dat = '2006-07-18'

Select      DATEADD(day, 7 - @@DATEFIRST -DATEPART(weekday, @Dat), @Dat) FirstDayOfWeek,
DATEADD(day, 6 - DATEPART(weekday, @Dat), @Dat) LastDayOfWeek

0

LVL 75

Accepted Solution

Anthony Perkins earned 1000 total points
ID: 17114541
Oops, I forgot to allow for a different @@DATEFIRST in the second expression, it should be:

Select      DATEADD(day, 7 - @@DATEFIRST - DATEPART(weekday, @Dat), @Dat) FirstDayOfWeek,
DATEADD(day, 13 - @@DATEFIRST - DATEPART(weekday, @Dat), @Dat) LastDayOfWeek

Sorry for the multiple posts.
0

LVL 75

Assisted Solution

Aneesh Retnakaran earned 1000 total points
ID: 17114542
Hi altuwairqi2,

CREATE FUNCTION [dbo].[ufn_GetLastDayOfWeek] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111)
RETURN DATEADD(DD, 1 - DATEPART(DW, @pInputDate)+6, @pInputDate)
END
GO

select [dbo].[ufn_GetLastDayOfWeek]('20060716')

Aneesh R!
0

LVL 75

Expert Comment

ID: 17594867
dont you think splitting the points ...
:(
0

LVL 75

Expert Comment

ID: 17597781
Fine with me.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
###### Suggested Courses
Course of the Month13 days, 13 hours left to enroll