0

i try to disply time with the showing AM / PM format but i am unable to find any code can you please guide me

var dt = new Date();

var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.getElementById("dt").innerHTML = time;
<p id='dt'></p>
nmak18
  • 734
  • 5
  • 20
user3181077
  • 111
  • 7

3 Answers3

1

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds()+"  ";
time+= dt.getHours()>=12?"PM":"AM"
document.getElementById("dt").innerHTML = time;
<div id="dt"></div>
ellipsis
  • 11,498
  • 2
  • 13
  • 33
0

Just compare the hours to if its less than 12 and if so set a variable to either AM or PM. Note that the following has the leading 0 added to the mins and secs if required (the slice will only include the 0 if the length of the value is 1).

var dt = new Date();
var hrs = dt.getHours();
var hours = hrs % 12;



var mins = '0' + dt.getMinutes();
var minutes = mins.slice(-2);

var secs = '0' + dt.getSeconds();
var seconds = secs.slice(-2);

var amPm = hrs< 12 ? 'AM' : 'PM';

var time = hours + ":" + minutes + ":" + seconds + ' ' +  amPm; 


document.getElementById("dt").innerHTML = time;
<p id = "dt"></p>
gavgrif
  • 13,077
  • 2
  • 17
  • 22
0

Just check if the value less than 12, and keep the hours under 12 and return 12 instead of 0 by: (hours %12 || 12):

var dt = new Date();

var time = (dt.getHours()%12||12) + ":" + dt.getMinutes() + ":" + dt.getSeconds() + " " + (dt.getHours() < 12)===0?"AM" : "PM";
document.getElementById("dt").innerHTML = time;
FZs
  • 11,931
  • 11
  • 28
  • 41