Programming a real-time Clock using JavaScript

In this article, we look at how you can implement a real-time clock in JavaScript. Clocks are of utmost importance on websites where time plays a large factor, e.g: booking websites, e-commerce, etc.

In this post, you will learn how to create a Digital Clock in 24-hour and 12-hour formats using JavaScript.

HTML Code:

<div class="time">
        <div id="hours">00</div>
        <div id="minutes">00</div>
        <div id="seconds">00</div>
        <div id="ampm">00</div>
</div>

CSS Code:

.time {
            height: 100vh;
            display: flex;
            gap: 40px;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: 700;
        }

Javascript Code for 24 Hours:

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;
})

Javascript Code for 12 Hours With AM/PM:

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.

RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply