32
In this post, you will learn how to create a Digital Clock in 24-hour and 12-hour formats using JavaScript.
<div class="time">
<div id="hours">00</div>
<div id="minutes">00</div>
<div id="seconds">00</div>
<div id="ampm">00</div>
</div>
.time {
height: 100vh;
display: flex;
gap: 40px;
align-items: center;
justify-content: center;
font-size: 1.5rem;
font-weight: 700;
}
setInterval(() => {
// time
let hours = document.getElementById("hours");
let minutes = document.getElementById("minutes");
let seconds = document.getElementById("seconds");
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
hours.innerHTML = h;
minutes.innerHTML = m;
seconds.innerHTML = s;
})
setInterval(() => {
// time
let hours = document.getElementById("hours");
let minutes = document.getElementById("minutes");
let seconds = document.getElementById("seconds");
let ampm = document.getElementById("ampm");
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let am = h >= 12 ? "PM" : "AM";
//convart time 12 hours
if (h > 12){
h = h - 12;
}
// add zero
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
hours.innerHTML = h;
minutes.innerHTML = m;
seconds.innerHTML = s;
ampm.innerHTML = am;
})
Note: In this article, we look closely at the JavaScript code behind a clock. We do not talk about CSS styling. We rather focus on the JavaScript code.
Here is is the full example
CSS hover effects allow elements to load quickly. Most web designers prefer CSS animations as they are easy to employ.