Add 3 months to date.

arobertson
Tera Guru

Hi All,

I'm struggling to add 3 months to an existing date field. The following code below should look up the user and add 3 months to their eligibility date.

DELSetEligibilityOnAssignment();

function DELSetEligibilityOnAssignment() {

  var gr = new GlideRecord('sys_user');

  gr.addQuery('sys_id', current.assigned_to);

  gr.query();

  var gdt = new GlideDateTime(gr.u_eligibility_date.getGlideObject());

  gdt.addMonths(3);

  if (gr.next()) {

  if (current.u_reason_for_assigning == 'Lost') {

  gr.u_work_notes = "Eligibility date changed on " + current.asset_tag + " for the following reason: " + current.u_reason_for_assigning + ".";

  gs.log("Before " + gdt + gr.u_eligibility_date);

  gr.u_eligibility_date = gdt;

  gs.log("After " + gdt + gr.u_eligibility_date);

  gr.u_last_upgrade_date = gs.now();

  gr.update();

  }

  }

}

24 REPLIES 24

Hi Greg,



The GlideDateTime parameter format is   YYYY-MM-DD HH:MM:SS


Link to example : GlideDateTime - ServiceNow Wiki



Regards,


Hardik Vora


Hi Hardik,



I'm aware of that just thought I've missed something after reading your post and hoped that it's somehow possible.




Cheers



Greg


Hi Greg,



Yes it works. A short example of import steps:   (I wrote an incident OnDisplay BR to test this)



1. Create a Glide Date Time object: (for testing i read the incident opened at date time)


                            var gdt = new GlideDateTime(current.opened_at.getDisplayValue());  



2. Perform the add function


                            gdt.addMonthsLocalTime(3);



3. Display the new value in any field:   (for testing i tried on short description)


                            current.short_description = gdt.getValue();



Regards,


Hardik Vora


Hi Hardik,



Yes, I know it works for that format I was talking about Alex's case.




Cheers



Greg


User179407
Mega Guru

Hi Alex,



Try this, we have used the below code to add 3 months to a date field



function onBefore(current, previous) {


  var threeMonthsFromNow = new GlideDateTime();


  threeMonthsFromNow.addMonths(3);



  current.u_3_month_review = threeMonthsFromNow;



}



Let me know if this works.



Suraj Chauhan