Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Trying to Calculate Days remaining

jasonjones
Giga Contributor

All,

I'm trying to create a client script or business rule that calculates the difference of a Warranty Expiration Date and the current date to determine a "Number of Days remaining" on the warranty.

find_real_file.png

I found this script in community to modify, but I'm still missing something.

function onChange(control, oldValue, newValue, isLoading) {
    var strt = g_form.getValue(warranty_expiration);  //set this as current warranty date
    var end = new Date(now.getFullYear(), now.getMonth(), no.getDate());  //This retrieves the current date
    var ajax = new GlideAjax('AjaxDurCalc');
    ajax.addParam('sysparm_name','durCalc');
    ajax.addParam('sysparm_strt',strt);
    ajax.addParam('sysparm_end',end);
    ajax.getXMLWait();
    var answer = ajax.getAnswer();
    g_form.setValue('u_days_of_remaining_warranty', answer);
}

Below is an error that is received.

find_real_file.png

Any help is appreciated.

Jason

41 REPLIES 41

Mike Patel
Tera Sage

If you are using business rule than you need something liek below

 

var gdt1 = new GlideDateTime(current.warranty_expiration.getDisplayValue());
var gdt2 = new GlideDateTime();
current.u_days_of_remaining_warranty = gs.dateDiff(gdt1, gdt2, false);

I'll try that.  I found something else where I was getting close.

 

var gdt = new GlideDate();
gdt.getDisplayValue("warranty_expiration");
var gdt2 = new GlideDate();
gdt2.getValue(NowDate);

current.u_days_of_remaining_warranty = GlideDateTime.subtract(gdt, gdt2);

jasonjones
Giga Contributor

Current Script. Still not working.

var gdt = new GlideDate(current.warranty_expiration.getDisplayValue());
var gdt2 = new GlideDate();
current.u_days_of_remaining_warranty = gs.dateDiff(gdt, gdt2, false);

u_days_of_remaining_warranty is a "String" variable.  Should it be that?

 

Yes, it needs to be duration type. I tested my script in background script and it gives me correct value

also if it's onAfter business rule you need to add

current.update(); which is not recommended so try changing it to onBefore rule