0

我正在创建一个 JS 时钟/日期。我以前有时间完美地工作,然后我决定在我的时钟(日期)上添加更多。现在我无法弄清楚为什么它不起作用。如果有人能给我提示或想法如何解决它,我将不胜感激。

function timedate()
    {
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var dn="PM"
    var d = currentTime.getDate(); <--
    var day = (d < 10) ? '0' + d : d;
    var m = currentTime.getMonth() + 1; <--
    var month = (m < 10) ? '0' + m : m;
    var yy = currentTime.getYear(); <--
    var year = (yy < 1000) ? yy + 1900 : yy;
    if (hours<12)
 {
    dn="AM"
 }
    if (hours>12)
 {
    hours=hours-12
 }
    if (hours==0)
 {
    hours=12
 }
    if (minutes<=9)
 {
    minutes="0"+minutes 
 }
 var clocklocation = document.getElementById('timedate');
 clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
 setTimeout("timedate()", 1000); 
    }
timedate();
4

2 回答 2

2

您的代码有效,只是不可见,因为您没有显示秒数

也改变

setTimeout("timedate()", 1000); 

setTimeout(timedate, 1000); 

因为不推荐

并删除 <--

确保它在加载时运行或在要显示它的标签之后运行

或者删除该行并更改

timedate();

setInterval(timedate,1000)

const pad = num => ("0" + num).slice(-2);
const timedate = () => {
  const currentTime = new Date();
  let hours = currentTime.getHours();
  const minutes = pad(currentTime.getMinutes());
  const seconds = pad(currentTime.getSeconds());

  const d = currentTime.getDate();
  const day = pad(d);
  const month = pad(currentTime.getMonth() + 1);
  const yy = currentTime.getFullYear();

  let dn = "PM"
  if (hours <= 12) dn = "AM";
  if (hours >= 12) hours -= 12;
  if (hours == 0) hours = 12;
  hours = pad(hours);
  document.getElementById('timedate').innerHTML = "" +
    hours + ":" +
    minutes + ":" +
    seconds + dn + " " +
    day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
  setInterval(timedate, 1000);
});
<span id="timedate"></span>

于 2013-04-13T21:21:21.583 回答
0

如果您使用setTimeout(timedate, 1000)而不是当前的魔术字符串版本设置超时,则可以使用1


1我还冒昧地在您的代码中添加了秒数,以明确时钟更新。当然,您还需要<--从代码中删除。

于 2013-04-13T21:23:27.447 回答