Get Next Sunday | Get Last Weekday

Example scripts and tips (replaces Old Scripts & Tips archive)

Moderators: Dorian (MJT support), JRL, Phil Pendlebury

Post Reply
User avatar
Dorian (MJT support)
Automation Wizard
Posts: 1394
Joined: Sun Nov 03, 2002 3:19 am
Contact:

Get Next Sunday | Get Last Weekday

Post by Dorian (MJT support) » Mon Mar 01, 2021 1:22 pm

Recently over at support we'd had a couple of questions asking how to figured out when the last weekday was, and when the next Sunday is.

I thought these examples may help :

Get Next Sunday.
Using DayofWeek, Sunday is day 1, Monday is day 2, and so on. All we need to do is get today and subtract it from 8.

Then add that number of days. So Monday is day 2, 8-2=6, so we add 6 days. Tuesday is 3, 8-3=5, we add 5 days, etc.

We use GetDate to get today's date, and DateAdd for adding dates.

Code: Select all

//Get the date
GetDate>Today

//What day is it? (1/2/3/4/5/6/7)
DayofWeek>TheDay

//Tests to double check our work
//sun day1/+7, mon day2/+6, tue day3/+5, wed day4/+4, thu day5/+3, fri day6/+2, sat day7/+1
//Simulate today being Wednesday (Day4)
//Let>TheDay=4

//Find the difference between today (TheDay) and Sunday (Day1)
Let>TheDifference=8-TheDay

//Add TheDifference to today
DateAdd>Today,D,TheDifference,NextSunday

MessageModal>The next Sunday is %NextSunday%

Get last weekday.
We can use similar logic for finding the last weekday. If today is Tuesday-Saturday (Day3-Day7), then the last weekday was today -1 day. Monday (Day2) would be -3 days, Sunday (Day1) -2 days.

Code: Select all

//Get the date
GetDate>Today

//What day is it?
DayofWeek>TheDay

//If it's Tuesday - Sat, increment is -1 day
If>{(%TheDay%>2) AND (%TheDay%<8)}
  Let>Increment=-1
Endif

//If it's Monday, increment is -3 days
If>TheDay=2
  Let>Increment=-3
Endif

//If it's Sunday, increment is -2 days
If>TheDay=1
  Let>Increment=-2
Endif

//Subtract the relevant number of days
DateAdd>Today,D,%Increment%,PreviousWeekDate


MessageModal>The last weekday date was %PreviousWeekDate%
Yes, we have a Custom Scripting Service. Message me or go here

Post Reply
Sign up to our newsletter for free automation tips, tricks & discounts