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.

How to populate duration filed on change request

Kartik Magadum
Kilo Sage

Hello,

 

I am currently using the following script (BR) to calculate the difference between the end date and the start date.

The field where I want to display this difference is in the Duration field on the change request form.

 

The backend name of the field where I'm calculating the difference is "calendar_duration," and its type is "Duration."

 

//Background script

var change = new GlideRecord('change_request');
change.addQuery('sys_id','c83c5e5347c12200e0ef563dbb9a7190');
change.query();
if(change.next())
{
var startdate = new GlideDateTime(change.start_date);
var enddate = new GlideDateTime(change.end_date);

var dur_seconds = gs.dateDiff(startdate, enddate, true);

gs.info(dur_seconds);
gs.info('Total difference in hrs ' + dur_seconds/3600);
}

//ANS of background script
*** Script: 91800
*** Script: Total difference in hrs 25.5
//Business rule 

(function executeRule(current, previous /*null when async*/ ) {
    var startdate = new GlideDateTime(current.start_date);
    var enddate = new GlideDateTime(current.end_date);
    var dur_seconds = gs.dateDiff(startdate, enddate, true);

    var duration = dur_seconds / 3600;

    //current.calendar_duration = duration;
    //current.cab_recommendation = duration + ' hrs';

})(current, previous);

Duration.png

 

Please note that my script is functioning correctly; I have tested it in a background script. I just need assistance with populating the duration field in the correct format. 

 

Any assistance in resolving this issue would be greatly appreciated.

 

Thanks and Regards

Kartik Magadum

1 ACCEPTED SOLUTION

Kartik Magadum
Kilo Sage

Hello

I have arrived at a solution by using the following code:

 

    var startDate = current.start_date.getGlideObject();
    var endDate = current.end_date.getGlideObject();
    current.calendar_duration = gs.dateDiff(startDate.getDisplayValueInternal(), endDate.getDisplayValueInternal(), false);

Duration 1.png

 Thanks and Regards

Kartik Magadum

View solution in original post

5 REPLIES 5

Wind0004
Mega Guru

Hi All, 

This may be a bit late but I did find a way to do this via calculated fields. 

This script is similar and created on the dictionary override for change request table. 

gs.dateDiff(current.work_start,current.work_end,false);

I have created a short video to demonstrate it working. Hope it helps. 

https://youtu.be/nrNnV1-y97U?feature=shared

 

Kind Regards,
Wind