如何用Javascript更改当前时间

时间:2017-11-25 13:48:24

标签: javascript html

我想在我的网页上显示当前时间。当我推F5时,我可以得到时间,但它没有改变。救救我..

HTML

      <div id="time" class="timer">
          show_time
       </div>

的Javascript

var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
   dn="AM";
if (hours>12)
   hours=hours-12;
if (hours==0)
   hours=12;
if (minutes<=9)
   minutes="0"+minutes;
if (seconds<=9)
   seconds="0"+seconds;
setInterval(setTime, 1000);
function setTime(){
    text2.innerHTML ="현재 시간: <br>"+ hours + ':' + 
    minutes + ':' + seconds+ "<bn>"+dn;
 }

setTime();

谢谢!

2 个答案:

答案 0 :(得分:0)

setTime

您必须在当前代码中添加一些内容,以便document.getElementById("time")函数实际将其输出添加到DOM。我使用ongoing child_0 id: "some id" 将函数中的时间添加到页面中。

答案 1 :(得分:0)

你需要获取函数内的当前时间,否则它将返回在第一次调用函数时得到的值

function setTime(){

var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
 dn="AM";
if (hours>12)
 hours=hours-12;
if (hours==0)
 hours=12;
if (minutes<=9)
 minutes="0"+minutes;
if (seconds<=9)
 seconds="0"+seconds;

  text2.innerHTML ="현재 시간: <br>"+ hours + ':' + 
  minutes + ':' + seconds+ "<bn>"+dn;
}

setTime();

setInterval(setTime, 1000);

https://jsfiddle.net/1gc8ymkd/