Using Variable to Add Days with Script

melinda_owen
Giga Contributor

Hi, I'm not sure I'm posting this in the correct forum since I felt it could go in a number of places. My scenario is:

I have a Date variable (u_term_date) that gets filled in on the first task of my workflow, after my RITM has been created, it's for a contract termination date. I need my second task to wait to generate until 90 days after this term date variable. 

I have added a duration field to be hidden on my RITM so it can hold the value of the date for the 90 days added and the workflow Timer can wait until that duration field. I am having trouble with my script and would love some assistance and feedback, please.

Here is my script currently inside my Timer activity.

if(current.variables.u_term_date.getDisplayValue() < gs.nowDate()) {
 answer = true;
}
else{
answer = false;
}

I had included in my script the addDays() which it doesn't seem to be adding, since I included a gsLog after it to see if the addition happened, and it did not. It was still logging the original u_term_date. I am new to scripting inside ServiceNow, and more importantly, a complete novice to Date scripting. I have scoured the Community for related topics, and most are incorporating adding days/time to current date, which is not my goal. I've tried piecing together scripts and I've tried a couple different approaches, all to no avail. Any and all help is appreciated at this point.

If I need to include any further information, please let me know. Thank you

1 ACCEPTED SOLUTION

you need below script 

var now= new GlideDateTime();
var gdt = new GlideDateTime(current.variables.u_term_date); 
gdt.addDaysLocalTime(90); //adds 90 days to term date variable
var dur =  GlideDateTime.subtract(now, gdt);
answer = dur.getNumericValue();

View solution in original post

13 REPLIES 13

Thank you! Can that be modified to not run at a specific time, or is that recommended/best practice?

Since it's term I want all taken care of early in morning so their accounts are disabled asap. but it's on you to decide when you want it to run.

I think this would work, except I realized I should've asked this inside of CSM, as dateDiff isn't allowed in that scope, nor is addDays. I've substituted in addDaysLocalTime and it accepts that, but I am trying to figure out how to correctly use the GlideDateTime.subtract() method as a substitute.

 

Thank you so much for your help!

see 

https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDateTimeSubtract_GlideDateTime_GlideDate_Time

you need below script 

var now= new GlideDateTime();
var gdt = new GlideDateTime(current.variables.u_term_date); 
gdt.addDaysLocalTime(90); //adds 90 days to term date variable
var dur =  GlideDateTime.subtract(now, gdt);
answer = dur.getNumericValue();