**EDIT 10/04/2019** – Thank you to CAR from SFSE for pointing out my original code had a few weak points and needed to be updated. I have now updated my code to a much more elegant solution (and one that actually will work in all situations). I would ask that you go on and make sure to give him as well as Cameron Robert a +1 for pointing this out and providing an alternative solution.

There are a ton of neat little tricks thst can be done in AMPscript. A great example is this trick to figure out the first and last day of the current week.

Below is a quick snippet that will let you decide what day of the week you want your ‘week’ to begin on (Sun, Mon, Tues, etc…). This then will calculate the start/end date according to that input.

Keep in mind on an email, this will be based on when the AMPscript was run (at send time usually) and not at live view. To counter this, you can use Now(1) which will lock in the date according to send time.

%%[

SET @dayofWeekBegin = "Mon"

SET @Today = FormatDate(NOW(), "dddd")

SET @daysOfWeekString = "Sun|Mon|Tue|Wed|Thu|Fri|Sat"

SET @daysOfWeekRowset = BuildRowSetFromString(@daysOfWeekString, '|')

IF @Today == @dayofWeekBegin THEN

	SET @BeginDate = FormatDate(NOW(),'mm/dd/yyyy')

ELSEIF @Today == @dayofWeekEnd THEN

	SET @EndDate = FormatDate(NOW(),'mm/dd/yyyy')

ENDIF



FOR @i = 1 TO Rowcount(@daysOfWeekRowset) DO 

	SET @tempDay = Field(Row(@daysOfWeekRowset,@i),1)
	
	IF @dayOfWeekBegin == @tempDay THEN

		set @daySub = @i

	ENDIF

NEXT @i


FOR @a = 1 TO Rowcount(@daysOfWeekRowset) DO 

	SET @tempDay = Field(Row(@daysOfWeekRowset,@a),1)
	
	IF @Today == @tempDay THEN

		set @dateOffset = SUBTRACT(@a, @daySub)

	ENDIF

NEXT @a


IF @dateOffset != 0 THEN

	SET @dateOffsetBegin = SUBTRACT(@dateOffset, ADD(@dateOffset,@dateOffset))
	SET @dateOffsetEnd = SUBTRACT(6,@dateOffset)

ENDIF

IF EMPTY(@BeginDate) THEN

	SET @BeginDate = FormatDate(DateAdd(Now(),@dateOffsetBegin,'D'),'mm/dd/yyyy')

ENDIF

IF EMPTY(@EndDate) THEN

	SET @EndDate = FormatDate(DateAdd(Now(),@dateOffsetEnd,'D'),'mm/dd/yyyy')

ENDIF

]%%
Day of Week Begin %%=v(@dayofWeekBegin)=%%<br>
Today %%=v(@Today)=%%<br>
Day Sub %%=v(@daySub)=%%<br>
Date Offset %%=v(@dateOffset)=%%<br>
Date Offset Begin %%=v(@dateOffsetBegin)=%%<br>
Date Offset End %%=v(@dateOffsetEnd)=%%<br>
This is the beginning of the week: %%=v(@BeginDate)=%%<br>
This is the end of the week: %%=v(@EndDate)=%%<br>

This would output the following:

Day of Week Begin Mon
Today Fri
Day Sub 2
Date Offset 4
Date Offset Begin -4
Date Offset End 2
This is the beginning of the week: 09/30/2019
This is the end of the week: 10/06/2019
Tags: , ,
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments