如何获取自动刷新的日期

How to get date to auto refresh?

本文关键字:刷新 日期 何获取 获取      更新时间:2023-09-26

我正在尝试在页面上获取刷新日期,这样我就不必每天手动刷新它。我有这段代码,但它似乎不起作用。日期会显示,但日期更改时不会更新。作为参考,这正在BrightSign显示器上使用。谁能告诉我我做错了什么?我是一个JavaScript初学者,所以没有什么太复杂的:)

<script type="text/javascript">
<!-- 
function clockTick()    {
   currentTime = new Date();
   month = currentTime.getMonth() + 1;
   day = currentTime.getDate();
   year = currentTime.getFullYear();
   setInterval(clockTick, 1000);
   return (month + "/" + day + "/" + year);
}
document.write(clockTick());
//-->
</script>
您需要从

函数中取出setInterval,并在函数内的页面上设置时间,以便它每秒刷新一次:

function clockTick() {
  var currentTime = new Date(),
      month = currentTime.getMonth() + 1,
      day = currentTime.getDate(),
      year = currentTime.getFullYear(),
      hours = currentTime.getHours(),
      minutes = currentTime.getMinutes(),
      seconds = currentTime.getSeconds(),
      text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds);
  // here we get the element with the id of "date" and change the content to the text variable we made above
  document.getElementById('date').innerHTML = text;
}
// here we run the clockTick function every 1000ms (1 second)
setInterval(clockTick, 1000);
<span id="date"></span>

你可以试试这个:从外面打电话clockTick()

 function clockTick()    {
       currentTime = new Date();
       month = currentTime.getMonth() + 1;
       day = currentTime.getDate();
       year = currentTime.getFullYear();
      // alert("hi");
      document.getElementById('date').innerHTML=month + "/" + day + "/" + year;
    }
    
    setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>