This question already has answers here:
Current time formatting with Javascript
                            
                                (14个回答)
                            
                    
                2年前关闭。
        

    

这是一个Html和Javascript当前时间显示代码,我正在尝试为此添加AM:PM,但是它不显示我用于var ampm = toda.getampm();
如何正确显示此格式



上午9:59:42



function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + " : "  +  m + " : "  +  s ;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
startTime();

<div id="time"></div>

最佳答案

请尝试以下答案



function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  var ampm = h >= 12 ? 'PM' : 'AM';

  h = h % 12;
  h = h ? h : 12; // the hour '0' should be '12'
  m = m < 10 ? '0'+ m : m;

  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + " : "  +  m + " : "  +  s  + " " + ampm;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
startTime();

<div id="time"></div>

10-07 14:39