简体   繁体   中英

JavaScript codes to add hour, minute and seconds

I am trying to write a JavaScript code that takes input for Hour, minute and seconds and adds them to show the total hour, minute and seconds. If the total minute is greater than 60 total hour will get increases by 1. Similarly for seconds. But when the total minutes are over 60 Total hours are getting +2 instead of +1. My code is as below. Can anyone please let me know what went wrong.

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);
    }
  });  

You can do it with JavaScript alone

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM