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

Hey Chuck, I've done something similar(Using script include to set a datefield value from an onChange client script) but the only issue here is the date is returning as yyyy-mm-dd, but when I try to add the date manually the format is dd/MM/yyyy. I've tried almost everything to change the format but in vain...



Any help would be appreciated...!



Cheers


Suhas


Thanks Chuck, will try using this with GlideDate () function and pass the


desired date format as a parameter...


Note that GlideDate() setDisplayValue() method has a different set of parameters. It only accepts one and it must be in the user's display format.



Also note that most server side scripts run as 'system'.



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



If GlideDate() doesn't do what you need, you can copy the GlideDate() value to a GlideDateTime() variable and manipulate it there, and copy it back. I've done that before.


Hey Chuck, this is what I've done in the script include..



setQuarterlyValidDate: function() {


  var gr = new GlideDateTime();


  gr.addMonthsUTC(3).setDisplayValue("dd/MM/yyyy HH:mm:ss");


  gr.getDisplayValue();


  return this._convertToGlideDate(gr);


  },



  _convertToGlideDate: function (gdt){


  var gd = new GlideDate();


  gd.setValue(gdt.getValue());


  gd.getByFormat("dd/MM/yyyy");


  return gd;


  },


And this is the Client script...



var answer = response.responseXML.documentElement.getAttribute("answer");


g_form.setValue('u_review_date',answer);



Still, the Date field shows the value in 'yyyy-mm-dd' format & not in the 'dd/MM/yyyy format....   is there anything wrong???