0

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>

6

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

6 Comments

i got it Thank you sir
You should have subtracted 12 from the var h after treating the am/pm thing. 13pm is quite redundant, isnt it?
@VictorLiaFook , now it's ok ?
You will also need to limit h to values between 1 and 12 like this: h=h%12; h=h?h:12; after you have determined the AM / PM case.
@cars10m , check answer again , it's already there
|
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.