Reputation: 37
I'm trying to add the current time to a website using JS and I found a working solution but the problem is that it works for 24-hour format time and I'm struggling to figure out how I might modify it to display 12-hour format time... See Fiddle HERE: https://jsfiddle.net/7hjsaqdu/1/
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var x = new Date()
var x1 = x.getMonth() + 1 + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();
var hour = x.getHours();
var minute = x.getMinutes();
var second = x.getSeconds();
if (minute < 10) {
minute = '0' + minute;
}
if (second < 10) {
second = '0' + second;
}
var x3 = hour + ':' + minute + ':' + second
document.getElementById('ct').innerHTML = x3;
display_c();
}
HTML:
<body onload=display_ct();>
<span id='ct' ></span>
Upvotes: 0
Views: 116
Reputation: 41
You can use Date.prototype.toLocaleTimeString()
Mozilla Developer Docs
let formattedTime = date.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
});
document.getElementById('ct').innerHTML = formattedTime;
Upvotes: 1