How to add years to a Date Field Type from Start Date

lrossy31
Tera Expert

Hello all,

I will appreciate if anyone can collaborate providing some ideas on how to add years to a Date Field (Certification Expiration) from a Date Field (Date Trained).  I have tried the following but it is not working(Certification Expiration field stays blank after saving request):

1. Right click on the 'Valid Field'

2. Click on personalize Dictionary

3. On default Value tabs, write the script below (ensure that the 'Use dynamic default is unchecked) :

                  javascript: var dat = new GlideDate(); dat.setValue(gs.monthsAgo(-12));                                           

                  dat.getDisplayValue();

or

                javascript: var dat = new GlideDateTime('u_date_trained');   

               dat.setValue(gs.monthsAgo(-12));                                           

               dat.getDisplayValue();

or

                 javascript: var dat = new GlideDateTime(); dat.addYears(2);                                           

                  dat.getDisplayValue();

 

4. Save

 

Again, I will greatly appreciate if anyone has an idea to make this calculation.

 

1 ACCEPTED SOLUTION

this code worked for me in before update business rule:

(function executeRule(current, previous /*null when async*/) {

	// Add your code here
	var d1 = new GlideDate();
d1.setValue(current.u_d1);


var yr = d1.getYearNoTZ();
yr = yr + 1;
var s1 = d1.getValue();
s1 = yr+s1.substring(4);


current.u_d2 = s1;

})(current, previous);

 

result:

find_real_file.png

Hope this helps.

Thanks,

Ali

View solution in original post

12 REPLIES 12

Mark Stanger
Giga Sage

This should work as a default value...

javascript:gs.yearsAgo(-2);

Hello Mark,

Tried this as well on an existing case or when creating a new case and the value (date) doesn't populate.  I need to set it 2 years from Date Trained Field which could be before today's date.

Pavani Ponnada2
Tera Contributor

Hello. Below are the ServiceNow OOTB functions to add/subtract years and days. Hope this helps!

 

var d1 = new GlideDate(); //get current date
gs.info(d1);


var gcdt = new GlideCalendarDateTime(d1);
gcdt.addYearsLocalTime(3); //adding 3 years to current date. Negative sign here subtracts 3 years
gs.info(gcdt);


var gcdt2 = new GlideCalendarDateTime(gcdt);
gcdt2.addDaysLocalTime(-1); //removing one day from above three years date. Negative sign here subtracts 1 day
gs.info(gcdt2);