JavaScript时钟问题

时间:2015-12-19 18:56:58

标签: javascript time

我正在尝试创建一个显示2个国家/地区时间的时钟。

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta charset="utf-8" />
    <script>
      function disptime() {

        now = new Date()

        hours = now.getHours();
        hours = hours < 10 ? "0" + hours:hours;

        minutes = now.getMinutes();
        minutes = minutes < 10 ? "0" + minutes:minutes;

        seconds = now.getSeconds();
        seconds = seconds < 10 ? "0" + seconds:seconds;

        milli = now.getTime();
        millib = milli + (6*60*60*1000);

        bhutan = new Date();
        bhutan = setTime(millib);

        bhutanHours = bhutan.getHours();
        bhutanHours = bhutanHours < 10 ? "0" + bhutanHours:bhutanHours;

        document.getElementById("bhutanClock").innerHTML=bhutanHours+ " : " + minutes + " : " + seconds;
        document.getElementById("UKClock").innerHTML=hours+ " : " + minutes + " : " + seconds;

        setTimeout("disptime()",1000);

      }
    </script>
  </head>
  <body onload="disptime()">
    <p id="bhutanClock"></p>

    <p id="UKClock"></p>
  </body>
</html>

加载此页面时,为什么浏览器中看不到任何内容?

2 个答案:

答案 0 :(得分:5)

第一个错误:您需要在setTime对象上应用Date()

bhutan = bhutan.setTime(millib);

并且更改此部分,由于某种原因,它以整数显示为毫秒:

bhutan = new Date();
bhutan = new Date(bhutan.setTime(millib));

工作代码段

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <title></title>
  <meta charset="utf-8" />
  <script>
    function disptime() {

      now = new Date()

      hours = now.getHours();
      hours = hours < 10 ? "0" + hours : hours;

      minutes = now.getMinutes();
      minutes = minutes < 10 ? "0" + minutes : minutes;

      seconds = now.getSeconds();
      seconds = seconds < 10 ? "0" + seconds : seconds;

      milli = now.getTime();
      millib = milli + (6 * 60 * 60 * 1000);

      bhutan = new Date();
      bhutan = new Date(bhutan.setTime(millib));

      bhutanHours = bhutan.getHours();
      bhutanHours = bhutanHours < 10 ? "0" + bhutanHours : bhutanHours;

      document.getElementById("bhutanClock").innerHTML = bhutanHours + " : " + minutes + " : " + seconds;
      document.getElementById("UKClock").innerHTML = hours + " : " + minutes + " : " + seconds;

      setTimeout("disptime()", 1000);

    }
  </script>
</head>

<body onload="disptime()">

  <p id="bhutanClock">

  </p>

  <p id="UKClock">

  </p>


</body>

</html>
&#13;
&#13;
&#13;

现在完美无缺: http://output.jsbin.com/bemuyawivu

答案 1 :(得分:3)

问题在于行bhutan = setTime(millib);

未在全局范围内定义函数setTime。我相信您正在寻找bhutan.setTime(millib)

此外,setTimeout应替换为setTimeout(disptime, 1000);

工作fiddle