Date difference

sigmachiuta
Kilo Guru

I am trying to run a script when the time is within 1 minute of the due date time.   How can I make sure that I am comparing the correct values here?   I tried to run a background script that would show me the values to see why the script below is triggering almost immediately, but it returned null.

var gr= new GlideRecord('incident')

gr.addQuery('active', true);

gr.addQuery('number', 'INC00051753')

gr.query();

gs.print("date diff: " + gs.dateDiff(gr.due_date,gs.nowDateTime(), false));

var gr = new GlideRecord('incident');

gr.addQuery('active', true);

gr.addQuery('state', 'IN', '2,3,4' );

gr.query();

while(gr.next()){

var time = gs.dateDiff(gr.due_date.getDisplayValue(),gs.nowDateTime(),true);

time = parseFloat(time);

//set state

if( time <= 60) {

//set state

gr.state = 1;

gr.update();

}

}

1 ACCEPTED SOLUTION

coryseering
ServiceNow Employee
ServiceNow Employee

Right. dateDiff is a shortcut for a GlideDuration calculation:



GlideDuration gd = new GlideDuration(end.getNumericValue() - start.getNumericValue());



Depending on wether you want a numeric value or not, there is some conversion to a number then a string, but basically it's just "what is the amount of time I'd have to *add* to the start date to get to the end date". If your start date is in the past and your end date in the future, then you get a positive number. If you reverse them, you get a negative number (because you's have add a negative amount of time to the start date to get 'back' to the end date).



If you just want the *absolute value*, run the returned value through Math.abs():



var gr= new GlideRecord('incident');


gr.addQuery('active', true);


gr.addQuery('number', 'INC00051753');


gr.query();



if (gr.next())


      gs.print("date diff: " + Math.abs(gs.dateDiff(gr.getValue('due_date'), gs.nowNoTZ(), true)));


View solution in original post

11 REPLIES 11

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi,



Try the below script and let me know the outcome.


var gr= new GlideRecord('incident')  


gr.addQuery('active', true);    


gr.addQuery('number', 'INC00051753')  


gr.query();  


  while(gr.next())


{


gs.print("date diff: " + gs.dateDiff(gr.opened_at,gs.nowDateTime(), false));


}


yea totally forgot the gr.next()


I ran the script and scheduled the time 10 minutes in the future and the result was -18592.   It looks like the time it is comparing to is not right.   The time i set in the system was 13:55 and when i printed nowDAteTime i had 13:47 but I also printed out the time field and that result was 18:55   not the 13:55 I set in the record.


Hi,



Thanks for the update. Can you please use gr.opened_at.getDisplayValue() and check the results.


looking at the record                                       2015-08-14 10:44:35


printing from background script     2015-08-14 15:44:35