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.

Find difference between two dates in minutes

sonita
Giga Guru

I have two fields ( Glide date time) , called outage stat and outage end.

i have another field called Total Outage (in minutes).   This should be auto calculated based off the Outage Start and Outage End fields.

This is what I've done so far ; but doesn't work.

As this a n onchange client script, which field should i select as the change field?( start   I guess?)

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

    if (isLoading || newValue == '') {

          return;

    }

  var strt = g_form.getValue('u_outage_start');

  var end = g_form.getValue('u_outage_end');

  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_total_outage_in_minutes', answer);

   

}

8 REPLIES 8

saurabh1
Giga Contributor

Use below function in script include



var diff = gs.dateDiff(today,selecteddate, true);



the variable diff will be in seconds so you can covert it according to your requirement.




sample code:



checkdiffDate: function() {


      var today = gs.now();


             


              var selecteddate = this.getParameter('sysparm_past_date');


             


              var diff = gs.dateDiff(today,selecteddate, true);


             


              var answer = '';  


              if (diff/(60*24*60) >=2){


                      answer = 'valid';


              }  


                else {


                        answer = 'false';


                }  


                    return answer;


      },


It's working now , but i'm wondering if there is a way to calculate the difference in minutes?



3.12.1 Input Fields

Parameters:


  • startDate - a starting date to compare, in the current user's date format
  • endDate - an ending date to compare, in the current user's date format
  • boolean numericValue - if true, the return will be formatted in number of seconds; if false, the return will be formatted ddd hh:mm:ss.

3.12.2 Output Fields

Returns: if the numericValue boolean parameter is true, returns the difference between the two dates as an integer number of seconds; if false, returns the difference between the two dates in the format ddd hh:mm:ss.


3.13 dateDiff(String, String, boolean)

Calculates the difference between two dates. This method expects the earlier date as the first parameter and the later date as the second parameter; otherwise, the method returns the difference as a negative value. Note: Use getDisplayValue() to convert the strings to the expected format.


well.. not OOB (that I know of), but just divide it with 60 and you're fine 😃


You're right 😉