Open In App

How to Design Digital Clock using JavaScript?

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Clocks are useful elements for any UI if used in a proper way. Clocks can be used on sites where time is the main concern like some booking sites or some apps showing arriving times of trains, buses, flights, etc.

We will learn to make a digital clock using HTML, CSS, and JavaScript.

Approach

  • Create the webpage structure in HTML using a div tag containing a dummy time of the format “HH:MM: SS”.
  • Style the page with CSS using elements and classes defined in HTML.
  • In JavaScript, define a function showTime and render it every second using the JavaScript setInterval() method.
  • Create a new instance of time using JavaScript’s new Date().
  • Convert it into a string format and show the output.

Example: In this example, we have followed above above-explained approach

HTML
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="clock">8:10:45</div>
    <script>
        
setInterval(showTime, 1000);
function showTime() {
    let time = new Date();
    let hour = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
    am_pm = "AM";

    // Setting time for 12 Hrs format
    if (hour >= 12) {
        if (hour > 12) hour -= 12;
        am_pm = "PM";
    } else if (hour == 0) {
        hr = 12;
        am_pm = "AM";
    }

    hour =
        hour < 10 ? "0" + hour : hour;
    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;

    let currentTime =
        hour +
        ":" +
        min +
        ":" +
        sec +
        am_pm;

    // Displaying the time
    document.getElementById(
        "clock"
    ).innerHTML = currentTime;
}

showTime();

    </script>
</body>

</html>
style.css
#clock {
    font-size: 175px;
    width: 900px;
    margin: 200px;
    text-align: center;
    border: 2px solid black;
    border-radius: 20px;
}

Note: You can use digital fonts available online to make the clock look more beautiful. For that, you have to download their file into your project and then use the “font-face” property to use that custom font. 

Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Next Article

Similar Reads