Creating a loop and incrementing dates

NeilH2
Giga Guru

I'm trying to take a start and stop date from a record, get the difference (in days) then loop a bit of code until the loop matches the difference.

Problem i'm having is getting the loop to run and getting the date to increment.

Any suggestions?

var start = current.u_date;

  var stop = current.u_stop;

  //get the difference between 2 dates

  var dateDiff = gs.dateDiff(start, stop, false);

  gs.log('dateDiff = ' + dateDiff);

  var i;

  var insertDate;

  //create a loop

  while (i < datediff){

  //run insert script here

  var RunInsert = new GlideRecord('u_schedule');

  RunInsert.initialize();

  RunInsert.u_date = insertDate;

  insert();

  //increment the insert date by 1

  var gdt = start.getGlideObject();

  insertDate=gdt.addDays(1); //adding 1 day

  //add 1 to i

  i++;

  }

//repeat loop

3 REPLIES 3

Uncle Rob
Kilo Patron

I learned javascript only within the context of ServiceNow, so this might be completely stupid and off topic.



From what I know of javascript, your line 10 would be undefined.   Thus, would undefined evaluate as less than datediff like you ask in line 14?



Try var i = 1 ?


I've added var = 0 and it runs once in the loop but var = 1 doesnt.


Looking at the log i'm getting 3 0:00:02 as the dateDiff variable, Is there a way to change this to a integer value so its just a 3?


var start = current.u_date;  


var stop = current.u_stop;  


 


 


  //get the difference between 2 dates  


  var dateDiff = gs.dateDiff(start, stop, false);  


  gs.log('dateDiff = ' + dateDiff);   //comes out as 3 0:00:02 for 3 days



 


  var i = 0;  


  var insertDate = start;  


 


  //create a loop  


  while (i < dateDiff){  


  //run insert script here  


  var RunInsert = new GlideRecord('u_schedule');  


  RunInsert.initialize();  


  RunInsert.u_date = insertDate;  


  insert();  


 


  //increment the insert date by 1  


  var gdt = start.getGlideObject();  


  insertDate=gdt.addDays(1); //adding 1 day  


 


  //add 1 to i  


  i++;  


  }  


//repeat loop  


Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Neil,



Just to add. In the 19th line of code it should be RunInsert.insert();