html java脚本当前时间无法添加AM:PM

时间:2017-09-22 04:32:27

标签: javascript html time

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

示例

9:59:42 AM



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();
&#13;
<div id="time"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

尝试以下答案

&#13;
&#13;
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();
&#13;
<div id="time"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<html>

<body>

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

</body>

<script type="text/javascript">

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 am_pm= h >=12 ? "PM" : "AM";

  // add a zero in front of numbers<10

  m = checkTime(m);

  s = checkTime(s);

  document.getElementById('time').innerHTML = h + " : "  +  m + " : "  +  s + am_pm;

  t = setTimeout(function() {

    startTime()

  }, 500);

}

startTime();

</script>

</html>