0
How to display current dynamic time using JS?
4 Respuestas
+ 4
Do you want to show the current time and update it every second?
This HTML and JavaScript works:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Time Display</title>
<style>
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
let time = document.getElementById('time');
function displayTime() {
time.innerText = new Date().toISOString();
}
window.setInterval(displayTime, 1000);
});
</script>
</head>
<body>
<div id="time"></div>
</body>
</html>
If you really want time and to use current time zone, you could replace the displayTime function with this:
function twoDigits(num) {
if (num < 10)
return '0' + num;
else
return num % 100;
}
function displayTime() {
let now = new Date();
let hours = (now.getHours() + 24) % 12 || 12;
let minutes = twoDigits(now.getMinutes());
let seconds = twoDigits(now.getSeconds());
let formattedTime = hours + ':' + minutes + ':' + seconds;
time.innerText = formattedTime;
}
0
Nice code Josh Greig. I didnt know || returned the lowest of the operands.
Btw In the let hours line, isnt it enough:
let hours = now.getHours()%12;
0
For 12 noon and 12 midnight, you don't want 0:MM:SS, right?
12 % 12 is 0. 12:30AM is also 00:30 in the 24-hour clock.
0
True that haha Josh Greig 🙋. Then ill just add || 12.
let hours = (now.getHours() % 12) || 12;
The addition 24 that im pretty sure doesnt have any effect.