如何在电子表格的Google脚本中计算两次之间的持续时间

时间:2015-05-04 13:26:54

标签: javascript google-apps-script

我想创建一个自定义函数来计算两个小时或更长时间之间的持续时间。结果可能是积极的,也可能是消极的。

其他人可以在任何给定坐标中使用该功能而不受限于特定范围。

示例输入:

 Inputs:                 Output:
 A      B       C        D

-26:55  06:38   22:39   -04:16
 02:19  00:00   04:33    02:19

我尝试了很多替代方案:

function saldo(A,B,C) { // best desired...

if(A == 0) {
    return (-B)+C ;
}
else if (A<0 && (-A)<C && (-A)-C<B){
    return (A)+C-B;
}
else if (A<0 && (-A)>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 > 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 < 10) ? "0" + seconds : seconds;

    return hours + ":" + minutes + ":" + seconds;
}

1 个答案:

答案 0 :(得分:1)

您只需要2个输入即可找到两小时变量之间的差异。

我有一个小的javascript code snippet,它以hh:mm格式输入2个输入并输出差异。您可以为hh:mm:ss格式推断此逻辑。您可以重复调用该函数以求解3个或更多输入。

// Code snippet to calculate the difference between 2 inputs of time in hh:mm 24hrs format
// Author: Harish Narayanan
// Date: 04-May-2015

function getHourDiff(a, b) {
    if (!isValidHour(a) || !isValidHour(b)) {
        return "Invalid input(s)";
    }

    var h1 = a.split(":"), h2 = b.split(":");
    var h = 0, m = 0;
    h = h1[0] - h2[0];
    m = h1[1] - h2[1];

    if (h < 0) {
        h = -h; 
        m = -m;
    }
    if (h == 0) {
        m = Math.abs(m);
    }
    if (m < 0) {
        m = m + 60;
        h = h - 1;
    }

    return h+":"+m;
}

function isValidHour(hour) {
    hourPattern = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
    if (hour.match(hourPattern)) {return true;}
    return false;
}