JavaScript代码添加小时,分钟和秒

时间:2018-10-18 10:55:32

标签: javascript

我正在尝试编写一个JavaScript代码,该代码接受时,分和秒的输入,并将它们相加以显示总时,分和秒。如果总分钟数大于60,则总小时数将增加1。 但是,当总分钟数超过60时,总时数将变为+2,而不是+1。我的代码如下。谁能让我知道出了什么问题。

let currentSecond, currentMinute, currentHour, totalTimeInSecond;
let totalSecond, totalMinute, totalHour;
let arrHour, arrMinute, arrSecond;
totalSecond = 0;
totalMinute = 0;
totalHour = 0;

document
  .getElementById("secondValue")
  .addEventListener("keypress", function(mojo) {
    if (mojo.keyCode === 13) {
      totalHour += parseInt(document.getElementById("hourValue").value, 10);
      totalMinute += parseInt(document.getElementById("minuteValue").value, 10);
      if (totalMinute >= 60) {
        totalMinute = totalMinute - 60;
        totalHour++;
      }
      totalSecond += parseInt(document.getElementById("secondValue").value, 10);
      if (totalSecond >= 60) {
        totalSecond = totalSecond - 60;
        totalMinute++;
      }

      console.log(totalHour);
      console.log(totalMinute);
      console.log(totalSecond);

      //   currentHour = document.getElementById("hourValue").value;
      //   currentMinute = document.getElementById("minuteValue").value;
      //   currentSecond = document.getElementById("secondValue").value;
      //   console.log(currentHour);
      //   console.log(currentMinute);
      //   console.log(currentSecond);
    }
  });  

1 个答案:

答案 0 :(得分:0)

您可以单独使用JavaScript

console.clear();

d = new Date()
d.setUTCHours(12)
d.setUTCMinutes(61)
d.setUTCSeconds(62)
console.log(d.getUTCHours().toString().padStart(2, '0') 
  + ':' 
  + d.getUTCMinutes().toString().padStart(2, '0') 
  + ':' 
  + d.getUTCSeconds().toString().padStart(2, '0')
) // 13:02:02