0

I have the following javaScript which is showing the time in hours and minutes.

Is there a way of having an "am" or "pm" next to the time, dependent on whether it's before or after midday?

var t = new Date();
var time = document.getElementById("time");

time.textContent = t.getHours() + ":" + t.getMinutes();
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
pjk_ok
  • 618
  • 7
  • 35
  • 90

2 Answers2

1

Answer adapted from here.

var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
    min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
    hr -= 12;
    ampm = "pm";
}


var time = document.getElementById("time");

time.textContent = hr + ":" + min + ampm;
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
-1

use the "toLocaleTimeString()" method instead of the "getHours()" and "getMinutes()"

for example:

var t = new Date();
var time = document.getElementById("time");

time.textContent = t.toLocaleTimeString('en-US');

source: https://www.w3schools.com/jsref/jsref_tolocaletimestring.asp

hortig
  • 70
  • 4