修正NaN错误

时间:2018-08-21 08:43:54

标签: javascript html

我一直在解析代码中的不同组合。但是,我仍然收到NaN错误。我有这个计时器倒数功能,可以让我设定一天中的特定时间,并根据您现在的时间倒数。我究竟做错了什么?预先感谢!

时间的格式是军事时间。

function myTime1() {
  var hour = document.getElementById("hrs").value;
  var min = document.getElementById("mins").value;
  var sec = document.getElementById("sec").value;

  var timeNow = parseInt(hour + ":" + min + ":" + sec);
  var currentDate = moment().format("DD MM YYYY");
  var timeDateNow = currentDate + " " + timeNow;
  // document.write(currentDate + " " + parseInt(hour) + ":" + parseInt(min) + ":" + parseInt(sec));



  // Set the date we're counting down to
  var countDownDate = new Date(currentDate + " " + hour + ":" + min + ":" + sec).getTime();

  // Update the count down every 1 second
  var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
      minutes + "m " + seconds + "s ";

    // If the count down is over, write some text 
    if (distance < 0) {
      clearInterval(x);
      document.getElementById("demo").innerHTML = "EXPIRED";
    }
  }, 1000);
}
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<!DOCTYPE HTML>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

  <input type="number" id="hrs" value="00">
  <input type="number" id="mins" value="00">
  <input type="number" id="sec" value="00">
  <input type="button" id="btnTime1" onclick="myTime1()" value="Go">

  <p id="demo"></p>


</body>

</html>

1 个答案:

答案 0 :(得分:0)

var timeNow = parseInt(hour + ":" + min + ":" + sec)

timeNow变量将始终为0,对于所有数据投射都使用moment.js。