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.

Convert integer field to duration

John Reynolds
Mega Expert

I have an integer field that stores the value of two dates in seconds.

I would like to convert this integer field (seconds) into a duration field.

For example, result of the two dates is 150000.

How can I convert into a duration field to display as seconds, minutes, hours, days.

1 ACCEPTED SOLUTION

Surendra Raika1
Kilo Guru

I tried a client script for this so that as soon as you change the value of the integer it change the duration also:


find_real_file.png


Integer field is : u_integer_1


Duration field is : u_glide_duration_2



on change of integer Script is something like this:




function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
    return;
  }

    //Type appropriate comment here, and begin script below
    var inputSecondstemp = (g_form.getValue('u_integer_1'));
    var inputSeconds = parseInt(inputSecondstemp, 10);
    //old school get the variables in place
    var secondsInAMinute = 60.0;
    var secondsInAnHour = 60.0 * secondsInAMinute;
    var secondsInADay = 24.0 * secondsInAnHour;

    // extract days
    var days = Math.floor(inputSeconds / secondsInADay);

    // extract hours
    var hourSeconds = inputSeconds % secondsInADay;
    var hours = Math.floor(hourSeconds / secondsInAnHour);

    // extract minutes
    var minuteSeconds = hourSeconds % secondsInAnHour;
    var minutes = Math.floor(minuteSeconds / secondsInAMinute);

    // extract the remaining seconds
    var remainingSeconds = minuteSeconds % secondsInAMinute;
    var seconds = Math.ceil(remainingSeconds);

    var duration = (days.toString() + " " + hours.toString() + ":" + minutes.toString() + ":" + seconds.toString());

  g_form.setValue('u_glide_duration_2', duration);

}


View solution in original post

7 REPLIES 7

Prateek kumar
Mega Sage

Hello John


Try this:


function sec2str(t){


var d = Math.floor(t/86400),


h = ('0'+Math.floor(t/3600) % 24).slice(-2),


m = ('0'+Math.floor(t/60)%60).slice(-2),


s = ('0' + t % 60).slice(-2);


return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');


}



Please mark my response as correct and helpful if it helped solved your question.
-Thanks

Prateek, that worked perfectly.   Thanks!


Awesome john. Glad it worked for you. Cheers



Please mark my response as correct and helpful if it helped solved your question.
-Thanks

Hi Prateek ,

Where is this script supposed to be written ?