Internet Explorer中的Javascript倒计时计时器上的NaN

时间:2018-04-18 09:57:39

标签: javascript internet-explorer nan

我正在使用以下JavaScript作为倒数计时器,并且它在大多数浏览器中都运行良好,但我只是仔细检查了Internet Explorer,并且我显示“NaN”代替每个数字。

任何人都可以帮助解释IE中出现错误的地方,而不是将个别变量视为数字吗?

c.add(Calendar.DAY_OF_MONTH, 42);
c.add(Calendar.DAY_OF_MONTH, 70);
PowerMockRunnerDelegate

2 个答案:

答案 0 :(得分:1)

MDN discourages the use of a string in the date constructor因为并非所有浏览器都以相同的方式实现此目的。

如果你想使用日期字符串,我建议使用像momentjs这样的第三方库来解析这些字符串,以确保它适用于每个浏览器。

答案 1 :(得分:0)

只需标准化日期和时间

function getNormalisedDatetime(dString) { // yyyy-mm-dd hh:mm:ss
  var parts = dString.split(" ");
  var dParts = parts[0].split("-");
  var tParts = parts[1].split(":");
  return new Date(dParts[0],dParts[1]-1,dParts[2],tParts[0],tParts[1],tParts[2]);
}
function pad(num) {
  return ("0"+num).slice(-2);
}

// Set the date we're counting down to
var countDownDate = getNormalisedDatetime("2018-05-25 12:00:00").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 an 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);


  // Display the result in the element with id="countdown"
  document.getElementById("countdown").innerHTML = "" + pad(days) + " : " + pad(hours) + " : " +
    pad(minutes) + " : " + pad(seconds);

  // If the count down is finished, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
  }
}, 1000);
<span id="countdown"></span>