Add months to GlideDate

thisisauniqueus
Giga Expert

Hi

I want to add months to my start date until a target date like for example

var startDate = new GlideDate();

var endDate = new GlideDate();

endDate.setValue('2016-09-09');

while(startDate<=endDate){

//do some processing

startDate.addMonth(1); //this is not an actual method just added here for verbosity

}

basically i have to generate a record for every month between the startDate and endDate

Regards

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

Hi John,



It's not a clean solution, but you could convert the GlideDate object to a GlideDateTime and use addMonthsLocal() or addMonthsUTC(), then convert back to a GlideDate().



It's a bit messy. I'm not sure why GlideDate() doesn't have addDays(), addMonths(), and addYears() - or some variant of that. I wish it did and invite you to open an enhancement request.



Enhancement requests: Tell us how you would improve the ServiceNow product


View solution in original post

17 REPLIES 17

Chuck Tomasi
Tera Patron

Hi John,



It's not a clean solution, but you could convert the GlideDate object to a GlideDateTime and use addMonthsLocal() or addMonthsUTC(), then convert back to a GlideDate().



It's a bit messy. I'm not sure why GlideDate() doesn't have addDays(), addMonths(), and addYears() - or some variant of that. I wish it did and invite you to open an enhancement request.



Enhancement requests: Tell us how you would improve the ServiceNow product


thanks Chuck!



Regards


something like this?



var startDate = new GlideDate();



var endDate = new GlideDate();


endDate.setValue('2016-09-09');



var gdt_startdate = convertToGlideDateTime(startDate);


gs.print(gdt_startdate.getValue());



function convertToGlideDateTime(GlideDate date ){


var gdt = new GlideDateTime(date);


return gdt;


}



function convertToGlideDate(GlideDateTime gdt){


var gd = new GlideDate();


gd.setValue( gdt.getDisplayValue() );


return gd;


}




Regards


Close John.   Just a few tweaks and a new function to add dates and I think we're good.



var startDate = new GlideDate();


gs.print('startDate=' + startDate.getValue());



var endDate = new GlideDate();


endDate.setDisplayValue('2016-09-09');



var gdt_startDate = convertToGlideDateTime(startDate);


gs.print(gdt_startDate.getValue());


var new_startDate = addMonths(gdt_startDate, 2);


gs.print(gdt_startDate.getValue());



function convertToGlideDateTime(date ){


  var gdt = new GlideDateTime(date.getValue());


  return gdt;


}



function addMonths(dateTime, n) {


  return dateTime.addMonthsUTC(n);


}



function convertToGlideDate(gdt){


  var gd = new GlideDate();


  gd.setValue( gdt.getValue() );


  return gd;


}