Open In App

How to Design Digital Clock using JavaScript ?

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 app showing arriving times of trains, buses, flights, etc. The clock is basically of two types, Analog and Digital. We will be looking at making a digital one. 

Prerequisites

Approach

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






// Calling showTime function at every second
setInterval(showTime, 1000);
 
// Defining showTime funcion
function showTime() {
    // Getting current time and date
    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();




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
    "width=device-width, initial-scale=1.0">
    <title>Digital Clock</title>
    <link rel="stylesheet" href="clock2.css">
</head>
<body>
    <div id="clock">8:10:45</div>
 
    <script src="clock2.js"></script>
</body>
</html>




#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: Click here to check the live 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.


Article Tags :