Subtract two durations fields

folu
Kilo Contributor

Hi, could anyone kindly assist on how to subtract two duration fields? Below is my code.

var tw = new GlideAggregate("metric_instance");

var metricSysID = 'ebff7bda0f920300ea7087ece1050efc';

tw.addQuery('id', '3149a00c0f560300ea7087ece1050eb0');

//tw.addQuery('id', current.sys_id);

tw.addQuery('value', 'Work in Progress');

    tw.addAggregate("SUM", "duration");

    tw.groupBy("id");

    tw.query();

    if (tw.next()) {

var timeworked = tw.getAggregate("SUM", "duration");

var dur = gs.dateDiff(tw.opened_at, gs.nowDateTime());

//var diff = (parseInt(timeworked) - parseInt(dur));

var diff = gs.dateDiff(timeworked, dur);

gs.print(" Duration1: " + dur);

gs.print(" Duration2: " + timeworked);

gs.print("Difference: " + diff);

}

*** Script:   Duration1: 23:59:59

*** Script:   Duration2: 00:08:13

*** Script: Difference: 00:00:00

8 REPLIES 8

okay, so we need to calculate the difference for hours, minutes and seconds?


can you print duration value also before calculations?



{


var grd_duration= grd.getAggregate('SUM', 'duration');


  gs.log('Value of Duration:' + grd_duration);                     // This one is printing correct duration


/print duration value here


  duration = duration - grd_duration;


  gs.log('Total Value :'   + duration);   // This one is printing as NaN.


  }


Harish KM
Kilo Patron
Kilo Patron

if you want to calculate duration for hours find below logic. I was calculating for outage start and end date



// Duration in hours


var dur_seconds = gs.dateDiff(chgrst.u_outage_start.getDisplayValue(), chgrst.u_outage_end.getDisplayValue(), true); // returns the number of seconds as


String


outage_duration = Math.round(dur_seconds / 3600); // Math.round() is optional and will round the number to the nearest integer and stored as total hours


}


Regards
Harish

folu
Kilo Contributor

Thanks all,



I used the format below and it worked.



var duration = new GlideDuration('3 12:00:00');


var duration2 = new GlideDuration('03:00:00');


var answer = duration.subtract(duration2);



gs.info(answer.getDisplayValue());