Condition for Scheduled Jobs to run on Mondays during the month sanity check please!

Community Alums
Not applicable

I have been given the requirements of running some scheduled jobs on the first of the month (this one is easy) then on the first Monday of the Month, 2nd Monday of the Month, 3rd Monday of the Month and finally 4th Monday of the Month.  From a little bit of research on this I found the following.

1st Monday of the Month

if (new Date().getDay() == 1 && new Date().getDate() <= 7) {
       true;
    } else {
    	false;
    }


2nd Monday of the Month

if (new Date().getDay() == 1 && new Date().getDate() >= 8 && new Date().getDate() <= 14) {
   true;
} else {
	false;
}

 

3rd Monday of the Month

if (new Date().getDay() == 1 && new Date().getDate() >= 15 && new Date().getDate() <= 22) {
   true;
} else {
  false;
}

 

4th Monday Of the Month

if (new Date().getDay() == 1 && new Date().getDate() >= 22 && new Date().getDate() <= 28) {
   true;
} else {
	false;
}

 

Does anyone see anything wrong with this or is there a better way to script with the conditional?

1 ACCEPTED SOLUTION

Jupiter W
ServiceNow Employee
ServiceNow Employee

The 3rd Monday of the Month should check with 21 as the end Date instead of 22. 

if (new Date().getDay() == 1 && new Date().getDate() >= 15 && new Date().getDate() <= 21) {

 

If you don't make this correction, there will be overlaps in your code when it's the 22nd Day that is a Monday which will pass True for both the 3rd Monday of the month and 4th Monday of the month.

View solution in original post

4 REPLIES 4

Jupiter W
ServiceNow Employee
ServiceNow Employee

The 3rd Monday of the Month should check with 21 as the end Date instead of 22. 

if (new Date().getDay() == 1 && new Date().getDate() >= 15 && new Date().getDate() <= 21) {

 

If you don't make this correction, there will be overlaps in your code when it's the 22nd Day that is a Monday which will pass True for both the 3rd Monday of the month and 4th Monday of the month.

Community Alums
Not applicable

Nice Catch, thank you

 

James Chun
Kilo Patron

Hi @Community Alums,

 

So it should return false for the last Monday if there are 5 Mondays in a month?

Why not simply the condition to something like below:

if( new Date().getDate() == 1 && new Date().getDate() <= 28) //Return true for all Mondays if the date is anything below the 28th
{
	return true;
}
else
{
	return false;
}

 

Cheers

Community Alums
Not applicable

I could not do that. There are 5 scheduled jobs and each is different depending on the Monday that it runs.  It was not my favorite thing to do but it's what they requested.  If it was as easy as just run on Mondays it would not be a big deal, I could set a weekly flow to run but this was a bit different.