How to get next 3rd thursday in script

Neeraja2
Tera Contributor

Hello Everyone,

I have one requirement to set planned start date as next 3rd thursday for a change request created, when an email is received. How can we get the next 3rd thursday using script in servicenow?

4 REPLIES 4

_Gaurav
Kilo Sage

Hi @Neeraja2 

Can you please help us understand by giving an date example what is required?

 

Neeraja2
Tera Contributor

Hi Gaurav,
If an email received tomorrow, which means second Thursday, then planned start date should be next month first Thursday. Else If tomorrow is first Thursday, then planned start date should tomorrow.

SNAdmin47
Kilo Sage

Hi @Neeraja2 ,

 

This is from my cheat sheet for that kinda thing.... might help you?

 

Setting a scheduled job date

  1. Any day on the first day of the week…

new Date().getDay() == 1 && new Date().getDate() <=7

 

It checks to see if it is a Monday (new Date().getDay() == 1) and if it is less than or equal to 7 days into the month (new Date().getDate() <=7).

 

  1. 2nd Monday of the month…

new Date().getDay() == 2 && new Date().getDate() >=8 && new Date().getDate() <15;

 

  1. Quarterly on a specific date:

var gdt = new GlideDate(); //creates new date object

var m = gdt.getMonth();  //extracts the month

var d = gdt.getDayOfMonth();  //extracts the day

if((m == "2" || m == "5" || m == "8" || m == "11") & (d == "15")){

    answer = true;

}

 

One thing... bear in mind the numbering starts at 0, so the first day of the week would be a 0, January would be a 0.

Hi @Neeraja2  here is one way to get the first Thursday of a month. The main function skips to next month if the first Thursday is in the past.

 

(function() {
var gdt = new GlideDateTime();   // get current date time object

var firstTh = findFirstThursday(gdt);
var dofm = gdt.getDayOfMonthLocalTime();  // day of month

if (firstTh < dofm)  {  // if first Thursday is in the past, get next month's first Thursday
    gdt.addMonthsLocalTime(1);
    firstTh = findFirstThursday(gdt);
}
// gs.print(firstTh);
return firstTh;
})()

function findFirstThursday(gdt) { // find first Thursday given a date-time
    const THURSDAY = 3;      // Mon=0, Sun=6 change this if you want other weekdays
    var dofw = gdt.getDayOfWeekLocalTime() - 1;  // make day of week base 0 for easier compute
    var dofm = gdt.getDayOfMonthLocalTime();  // day of month
    var nextTh = ((THURSDAY - dofw)  + dofm) % 7 ;  // add days to next thursday 
    if (nextTh === 0 )  nextTh = 7;  // day 0 with base 0 is actually day 7
    // gs.print( gdt  + '/' + dofw  + '/' + nextTh);

    return nextTh;
}

 

Hope this helps

If this answer solved your issue please mark it as a solution or mark it 👍 helpful if it was of help.

--

Bala Guthy