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 add two duration fields

manish123
Giga Guru

Hi All,

On Incident page, we have Time Card entry tab. And on that there is Duration field which is getting calculated from two other fields as Start Time and End Time. Therefore suppose a single incident should have multiple Duration added. Now on incident there is Total Duration field where i would like the addition of all these Duration for Time Card entries. Can anyone please let me know how can i do it?

33 REPLIES 33

marcguy
ServiceNow Employee
ServiceNow Employee

So because duration is just stored as an integer you should just be able to add all of these up by using +



So gliderecord query through the existing timecards and just keep adding the duration value up in each one to a total variable and then set that variable integer into your total duration value.



Var tot = 0; //declare that at the start so the tool knows you want an integer and then



While(timecard.next()){


tot = timecard.duration + tot;


}



Eventually once you've been through all of them you will have a total amount to enter into your parent.


OK however how do you convert integer into the duration format at last while displaying on proper field?


marcguy
ServiceNow Employee
ServiceNow Employee

as long as you enter the integer value into the duration field as long as this is server-side the tool will convert that integer and display it as a duration to anybody looking at it, all the tool is doing when you look at a duration field value on a form/list is converting that underlying integer value into something readable.


No It's not working. i think the issue is with its calculation only. Have you used it before. if so then can you please share the line of codes for same?


marcguy
ServiceNow Employee
ServiceNow Employee

Here's what I have in a before BR on incident to go through any child tasks and gather their durations(hours worked) up into the parent incident total time worked field.



var totalDur =0; declare as an integer


  var inc = new GlideRecord('task');


  inc.addQuery('parent',current.sys_id);


  inc.query();


  while(inc.next()) {


totalDur = totalDur + inc.u_hours_worked;


}


current.u_total_time_worked = totalDur




you can also do it quicker via a glideAggregate BR which is quicker



var totalDur =0; declare as an integer


  var tw = new GlideAggregate("task");


    tw.addQuery("parent", current.sys_id);


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


    tw.groupBy("task");


    tw.query();


    if (tw.next()) {


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




current.u_total_time_worked = timeworked;


}