Signup/Sign In

Build a Simple Digital Clock in JavaScript

Posted in Programming   LAST UPDATED: APRIL 28, 2023

    Building a digital clock using JavaScript can be an excellent project for a beginner to understand the basic concepts of JavaScript. Creating this will help you know about accessing the DOM, adding activity to them, and much more.

    So, let's start.

    Prerequisites

    • Basic HTML

    • Basic CSS

    • Little Knowledge of JavaScript

    What will we learn?

    • Creating Variables in JS

    • Accessing DOM in JS

    • Adding Properties to the DOM

    Here’s the preview of what we are going to build today.

     Simple Digital Clock with JavaScript

    As you can see, we have a clock that is centered. To achieve this, we'll be using CSS Flexbox here. If you are not familiar with Flexbox, check this our 2-part Flexbox series.

    HTML Clock Code

    Our HTML is a single line of code. We'll just add a container in which our clock will show up.

    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8"/>
    		<meta name="viewport" content="width=,initial-scale="/>
    		<link href="https://fonts.googleapis.com/css2?family=Lato:wght@900&display=swap" rel="stylesheet"/>
    		<title>Clock</title>
    	</head>
    	<body>
    		<div id="clock"></div>
    	</body>
    </html>

    Look at the code. The only thing we are adding except the boilerplate HTML is a div with an id of clock and a font using Google Fonts. We'll target this div to show up the digital clock using JavaScript.

    CSS Code

    In our CSS code we will provide styling for the body of our HTML page and for the clock.

    body {
    	margin: 0;
    	padding: 0;
    	box-sizing: border-box;
    	font-family: "Lato", sans-serif;
    }
    
    #clock {
    	height: 100vh;
    	width: 100%;
    	background-color: #14080e;
    	color: #e9eb9e;
    	display: flex;
    	align-items: center;
    	justify-content: center;
    	font-size: 50px;
    }

    Our CSS is also straightforward. First, we'll reset our page with the margin:0, padding:0 property. We are also adding the font family to the body. Next, we are styling our clock div.

    The height: 100vh will give the id a height of the complete viewport. We are also giving it a width of 100%. Then, we are adding a background color and a text color to it using the background-color and color property respectively.

    We want our clock to be centered on the page. To achieve this, we'll take the help of the CSS flexbox.

    First of all, we are invoking flexbox using the display: flex property, then to center the element through the main axis, we are using the justify-content:center property and to center it along the cross-axis, we are using the align-items:center property. And, finally, we are giving a font size of 100px. And we are done with the CSS.

    Now comes the most crucial part.

    JavaScript Clock Code

    Before writing the JavaScript part, let’s understand a few basics that we’ll need here.

    The Date Object:

    The Date object is a JavaScript object that represents the date and time. Inside the object, the date is stored as a number in milliseconds since 1st January 1970.

    To create the Date object, we use the Date constructor. Creating a new Date object will return the current date and time.

    Example:

    let date = new Date();
    
    console.log(date)


    Mon Oct 05 2020 22:28:08 GMT+0530 (India Standard Time)

    The output will change depending on your locale.

    This Date object has multiple methods on it. These methods are used to extract different values from the object. For example, to extract the hour from the object, we have a method called getHours().

    Similarly, getMinutes() method will give us the minutes, and the getSeconds() will provide the seconds. Another thing to note while using the Date object is that it'll return the hour in 24-hour format.

    Now, let’s start writing the JavaScript part.

    We’ll be creating the whole code inside a function. We are using the ES6 arrow functions here. If you don't know what JavaScript arrow functions are, here's an awesome article about it.

    let clock = () => {
      let date = new Date();
      let hrs = date.getHours();
      let mins = date.getMinutes();
      let secs = date.getSeconds();
      let time = `${hrs}:${mins}:${secs}`
      // log the time in console
      console.log(time)
    }
    // call the clock function
    clock();

    As you can see from the above code, we are storing the Date object inside a variable called date and then calling different methods over the object to get the distinct values. We are holding the values inside variables. We are creating another variable called time, where we are concatenating the hours, minutes, and seconds using template literals. To check if we are getting the correct output, we are console-logging the time variable.

    Our clock is almost ready. But it is in a 24-hour format for now. To make it a 12-hour clock, we’ll be taking the help of conditional statements. But before writing the condition, we’ll declare another variable to keep track of AM or PM. Let's call it period here.

    The Condition

    let period = "AM";
    if (hrs == 0) hrs = 12;
    
    if (hrs > 12) {	    
    	hrs = hrs - 12;	    
    	period = "PM";	  
    }

    What are we doing in the condition? If hours is 0 (i.e., the midnight 0th hour), we set the hrs to 12, and if it's greater than 12, we calculate the hour using hrs - 12 and also set the period to PM. So, our clock is ready for the 12-hour format. To make it look better, we’ll also be adding a zero in front of the numbers whenever the number is less than 10. We’ll use the JavaScript ternary operator for that. We can also do it using conditionals, but it would require us to write more code.

    hrs = hrs < 10 ? `0${hrs}` : hrs;
    mins = mins < 10 ? `0${mins}` : mins;
    secs = secs < 10 ? `0${secs}` : secs;

    As you can see, whenever the number is less than 10, we are concatenating the number with a 0 in front of it, and otherwise, we set the value that we are getting. Now, how do we show it in the browser? Here comes the use of DOM.

     document.getElementById("clock").innerText = time;

    First, we are targeting the DOM with the help of the div ID of the clock, and then we are assigning an inner text to the div using the innerText setter. We are setting the time variable as the inner text. We’ve also added the period to the time variable.

    So, our clock is almost ready. But if you check the browser now, you’ll find that the clock is stuck in a particular time. It is not changing. Why? Because the Date object is storing the value once and not changing it. To solve this issue, we’ll need a JavaScript function called setInterval. This function evaluates a function repeatedly after a given time. We will pass two arguments into setInterval for this example, the first argument will be the function that has to be executed, and the second argument is the time after which we want to execute it again and again.

    setInterval(clock, 1000)

    The setInterval function takes time as milliseconds. We want to execute the clock function after every 1 second. So, we are passing the clock as the first parameter and 1000(i.e., 1 second) as the second parameter.

    And our clock is ready.

    Final JavaScript Code

    let clock = () => {
      let date = new Date();
      let hrs = date.getHours();
      let mins = date.getMinutes();
      let secs = date.getSeconds();
      let period = "AM";
      if (hrs == 0) {
        hrs = 12;
      } else if (hrs >= 12) {
        hrs = hrs - 12;
        period = "PM";
      }
      hrs = hrs < 10 ? "0" + hrs : hrs;
      mins = mins < 10 ? "0" + mins : mins;
      secs = secs < 10 ? "0" + secs : secs;
    
      let time = `${hrs}:${mins}:${secs}:${period}`;
      document.getElementById("clock").innerText = time;
      setTimeout(clock, 1000);
    };
    
    clock();
    

    Now that we know how to implement this. Below we have a live working code for this. Try to run it to see the code in action and try making changes to the code to customize the clock.

    Conclusion

    I hope you learned something new from this article. If you enjoyed it, do check the building a theme switcher article.

    If you want to practice your JavaScript programming skills by creating projects in JavaScript, check out these -

    Frequently Asked Questions(FAQs)

    1. How to create a digital clock using HTML CSS and JavaScript?

    Creating a digital clock using HTML, CSS, and JavaScript:

    <div class="clock-container">
      <div class="clock">
        <span id="hours">00</span>:
        <span id="minutes">00</span>:
        <span id="seconds">00</span>
      </div>
    </div>
    

    CSS:

    .clock-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .clock {
      font-size: 6rem;
      font-family: 'Arial', sans-serif;
      color: #fff;
      background-color: #000;
      padding: 2rem;
      border-radius: 1rem;
    }
    

    JavaScript:

    function updateTime() {
      var now = new Date();
      var hours = now.getHours();
      var minutes = now.getMinutes();
      var seconds = now.getSeconds();
    
      hours = ('0' + hours).slice(-2);
      minutes = ('0' + minutes).slice(-2);
      seconds = ('0' + seconds).slice(-2);
    
      document.getElementById('hours').innerHTML = hours;
      document.getElementById('minutes').innerHTML = minutes;
      document.getElementById('seconds').innerHTML = seconds;
    }
    
    setInterval(updateTime, 1000);
    

    2. How to create a wall clock using JavaScript?

    Creating a wall clock using JavaScript:

    HTML:

    <div class="clock-container">
      <div class="clock">
        <div class="hour-hand"></div>
        <div class="minute-hand"></div>
        <div class="second-hand"></div>
      </div>
    </div>
    

    CSS:

    .clock-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .clock {
      width: 20rem;
      height: 20rem;
      background-color: #fff;
      border-radius: 50%;
      position: relative;
    }
    
    .hour-hand,
    .minute-hand,
    .second-hand {
      position: absolute;
      left: 50%;
      top: 50%;
      transform-origin: bottom center;
    }
    
    .hour-hand {
      width: 0.5rem;
      height: 5rem;
      background-color: #000;
      margin-left: -0.25rem;
    }
    
    .minute-hand {
      width: 0.25rem;
      height: 7.5rem;
      background-color: #000;
      margin-left: -0.125rem;
    }
    
    .second-hand {
      width: 0.1rem;
      height: 9.5rem;
      background-color: #f00;
      margin-left: -0.05rem;
    }
    

    JavaScript:

    function updateClock() {
      var now = new Date();
      var hours = now.getHours();
      var minutes = now.getMinutes();
      var seconds = now.getSeconds();
    
      var hourAngle = (hours % 12) * 30 + (minutes / 2);
      var minuteAngle = minutes * 6;
      var secondAngle = seconds * 6;
    
      document.querySelector('.hour-hand').style.transform = `rotate(${hourAngle}deg)`;
      document.querySelector('.minute-hand').style.transform = `rotate(${minuteAngle}deg)`;
      document.querySelector('.second-hand').style.transform = `rotate(${secondAngle}deg)`;
    }
    
    setInterval(updateClock, 1000);
    

    3. How do you make a simple clock in HTML?

    To make a simple clock in HTML, you can use the <time> element, which is a semantic element that represents a date or time. Here's an example:

    <time id="clock"></time>
    
    <script>
    setInterval(function() {
      document.getElementById('clock').innerHTML = new Date().toLocaleTimeString();
    }, 1000);
    </script>
    

    This will create a clock that updates every second and displays the current time using the toLocaleTimeString() method.

    4. How do I display a digital clock in HTML?

    To display a digital clock in HTML, you can use the same basic steps as for a simple clock but with some additional styling to make the clock display look like a digital clock. Here's an example:

    <div id="clock"></div>
    
    <script>
    setInterval(function() {
      var time = new Date();
      var hours = time.getHours();
      var minutes = time.getMinutes();
      var seconds = time.getSeconds();
      var meridiem = "AM";
    
      if (hours > 12) {
        hours -= 12;
        meridiem = "PM";
      }
    
      if (hours === 0) {
        hours = 12;
      }
    
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
    
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
    
      var clockDisplay = hours + ":" + minutes + ":" + seconds + " " + meridiem;
      document.getElementById("clock").innerHTML = clockDisplay;
    }, 1000);
    </script>
    

    This will create a digital clock that updates every second and displays the current time in the format "HH:MM:SS AM/PM".

    You may also like:

    About the author:
    Subha Chanda is a talented technical author who specializes in writing on the JavaScript programming language and JavaScript games. Through his work, Subha seeks to share his knowledge and inspire others to explore the vast potential of JavaScript.
    Tags:htmljavascript
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS