core114 core114 - 27 days ago 11
Javascript Question

html java script current time to cant add AM:PM

This is a Html and Javascript current time display code, I am trying to add

AM:PM
for this, but it does not display I am used for
var ampm = toda.getampm();

how to display correctly this format

example

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();

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




Answer Source

Try below answer

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>