title: How to calculate duration between two times in Google scripts for spreadsheet
body: <p>I would like to create a custom function that calculates the duration between two or more hours. The result can be positive or negative.</p>
  
  <p>Other people can benefit using the function in any given coordinates not limiting to a specific range.</p>
  
  <p>Example input:</p>
  
  <pre><code> Inputs:                 Output:
   A      B       C        D
  
  -26:55  06:38   22:39   -04:16
   02:19  00:00   04:33    02:19
  </code></pre>
  
  <p>I've tried without success many alternatives:</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>function saldo(A,B,C) { // best desired...
  
  if(A == 0) {
      return (-B)+C ;
  }
  else if (A&lt;0 &amp;&amp; (-A)&lt;C &amp;&amp; (-A)-C&lt;B){
      return (A)+C-B;
  }
  else if (A&lt;0 &amp;&amp; (-A)&gt;C){
      return (-B);
  }
  
  
  function xis(A,B) {
  
  // var addedDate = sheet.getRange(1,1).getValue();
  //  var a1 = Utilities.formatDate(A, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");  
  //  var b1 = Utilities.formatDate(B, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");   
  
  
  var a1 =  new Date.getHours(A) + date.getMinutes(A);
  var b1 =  new Date.getHours(B) + date.getMinutes(B);
  
    if (a1 &gt; b1){
  
      return B;
    }
  
    else {
      return A;
    }
  
  }
  
  
  
  function tentativa(a,b){
    var t1 = a.getTime();
    var t2 = b.getTime();
  
  var outnumber =  t1 - t2;
  
    return Utilities.formatDate(new Date(outnumber), "GMT-3", "hh:mm");  
  }
  
  function worked(time1,time2)      
  {                                 
  //var time1;
  //var time2;
  var outnumber = time1 - time2;  
   // return msToTime(outnumber) 
    return msToTime(outnumber);
   //  return Utilities.formatDate(new Date(outnumber), "GMT", "HH:mm");  
  }
  
  function msToTime(duration) {
      var milliseconds = parseInt((duration%1000)/100)
         , seconds = parseInt((duration/1000)%60)
         , minutes = parseInt((duration/(1000*60))%60)
          , hours = parseInt((duration/(1000*60*60))%24);
  
    //  hours = hours : hours;
    //  minutes =  minutes : minutes;
    //   seconds = (seconds &lt; 10) ? "0" + seconds : seconds;
  
      return hours + ":" + minutes + ":" + seconds;
  }
  </code></pre>