DEV Community

Cover image for Build a Digital Clock Using HTML, CSS, and JavaScript
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Build a Digital Clock Using HTML, CSS, and JavaScript

The HTML contains a heading and a container where the current time will be displayed.

<div class="clock-container">
    <h1>Digital Clock</h1>
    <div id="clock">00:00:00</div>
</div>
Enter fullscreen mode Exit fullscreen mode
  • <h1> displays the title.
  • <div id="clock"> initially shows 00:00:00.
  • JavaScript updates this element every second. Style the Clock with CSS We use Flexbox to center the clock on the page and give it a clean card design.
body{
    height:100vh;
    display:flex;
    justify-content:center;
    align-items:center;
    background:#0f172a;
}
Enter fullscreen mode Exit fullscreen mode

Display the Current Time

function showTime() {

    let date = new Date();

    let hours = String(date.getHours()).padStart(2,'0');
    let minutes = String(date.getMinutes()).padStart(2,'0');
    let seconds = String(date.getSeconds()).padStart(2,'0');

    let time = `${hours}:${minutes}:${seconds}`;

    document.getElementById("clock").innerHTML = time;
}
Enter fullscreen mode Exit fullscreen mode
  • new Date()Creates a Date object containing the current date and time.
  • (Fri Jul 17 2026 14:35:42).
  • getHours() Returns the current hour.
  • getMinutes() Returns the current minutes.
  • getSeconds() Returns the current seconds.
  • padStart() Ensures every value contains two digits.
  • Without padStart(): 5:7:9
  • With padStart(): 05:07:09 Syntax
string.padStart(targetLength, padString)
Enter fullscreen mode Exit fullscreen mode
padStart(2,'0')
Enter fullscreen mode Exit fullscreen mode

2 Make the total length 2 characters.'0' If needed, add 0 on the left.
Template Literals

let time = `${hours}:${minutes}:${seconds}`;
Enter fullscreen mode Exit fullscreen mode

Combines the values into a time string.

09:15:42
Enter fullscreen mode Exit fullscreen mode

Update the HTML

document.getElementById("clock").innerHTML = time;
Enter fullscreen mode Exit fullscreen mode

Updates the content of the <div id="clock"> element with the latest time.
Update Every Second

setInterval(showTime,1000);
Enter fullscreen mode Exit fullscreen mode

setInterval() repeatedly executes a function.
Syntax:

setInterval(functionName,timeInMilliseconds);
Enter fullscreen mode Exit fullscreen mode

Since 1000 milliseconds equals 1 second, the clock refreshes every second.
Show the Time Immediately

showTime();
Enter fullscreen mode Exit fullscreen mode

Without this line, the page would display:

00:00:00
Enter fullscreen mode Exit fullscreen mode

until the first second passes.Calling showTime() immediately displays the correct time as soon as the page loads.

Top comments (0)