计算时差并使用Javascript对差值求和

时间:2018-03-27 07:28:09

标签: javascript time

我试图找到结束时间和开始时间的差异,然后添加所有时差

我可以知道我该怎么办?

代码如下

function THcheck() {
  var a, s, timeDiff, hr = 0;
  var hdate, startTime, endTime, totalTime, timeDiff;
  var output = "Date			StartTime:		EndTime:		TimeDiff <br>";
  var msg = "";

  var DStime, DEtime;

  var e = document.getElementsByTagName('input');

  for (a = 0; e !== a; a++) {
    if (e[a].type == "time" && e[a].name == "THStime[]") {
      if (e[a].value && e[a].value !== "") {

        startTime = e[a].value;
        endTime = e[a + 1].value;
        hdate = e[a - 1].value

        alert(hdate + " " + startTime + " " + endTime);

        timeDiff = endTime - startTime;

        alert(timeDiff);

        hr = parseInt(timeDiff.asHours());

        alert(timeDiff);

        totalTime += timeDiff;

        alert(totalTime);


        output += hdate + "   " + startTime + "   " + endTime + "   " + timeDiff + "<br>";


        if (hr >= 24) {
          msg = "<br> Exceed 24 hrs! ";
        }

      }
    }
  }
  alert(output + " Total time: " + totalTime + msg);
  return true;
}

提前感谢您的帮助和帮助!

1 个答案:

答案 0 :(得分:0)

我认为您需要先解析小时数,从字符串转换为日期,然后将日期转换为毫秒,并使用毫秒进行差异计算。在此之后,您将差异毫秒转换为小时。

以下是执行以下步骤的示例代码:

const dateRegex = /(\d{2}):(\d{2})/;

function diffDatesInHours(d1Str, d2Str) {
  const r1 = dateRegex.exec(d1Str);
  const r2 = dateRegex.exec(d2Str);
  if (!checkDate(r1)) {
    console.log("First date format incorrect: " + d1Str);
    return null;
  }
  if (!checkDate(r2)) {
    console.log("Second date format incorrect: " + d2Str);
    return null;
  }
  const d1 = createDateFrom(r1);
  const d2 = createDateFrom(r2);
  const diff = d1.getTime() - d2.getTime();
  return Math.abs(diff) / (1000 * 60 * 60);
}

function checkDate(r) {
  if (r === null) {
    return null;
  }
  return r.length > 0;
}

function createDateFrom(r) {
  let date = new Date();
  date.setHours(r[1], r[2]);
  return date;
}

console.log(diffDatesInHours("09:30", "21:00"));
console.log(diffDatesInHours("09:30", "21:"));