DEV Community

Boateng Dickson
Boateng Dickson

Posted on

Build A Real-time Changing Digital Clock Using HTML, CSS & JavaScript

HTML, CSS and JavaScript are used for building stylish, dynamic web elements and one useful element we can build is a digital clock.

In this tutorial, we would discuss how to build a simple real-time changing digital clock that displays the current time and date.

How to Build a Digital Clock using HTML, CSS and JS

We would start by establishing the HTML markup for our project.

We would create a folder called clock. Inside this folder, we would create three files: index.html, styles.css, and main.js. We would then link the two other files into our index.html file, as seen below:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <script src="app.js" type="text/javascript"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can copy the code above into your index.html file, or get the code for this project from Codepen

HTML Markup for our Clock

The HTML markup for our digital clock is pretty simple. It consists of an h1 element with an id of date-time wrapped around by a div element also with an id of clock.

<div id="clock">
  <h1 id="date-time"></h1>
</div>
Enter fullscreen mode Exit fullscreen mode

Nothing would display for our digital clock unless we bring in some JavaScript.

Adding JavaScript to our Clock

We're going to write some JavaScript at this point to bring our digital clock to life.

Let's go to our main.js file and paste the following code in there.

Please read the comments in the code for further clarification.

window.addEventListener("load", () => {
  clock();
  function clock() {
    const today = new Date();

    // get time components
    const hours = today.getHours();
    const minutes = today.getMinutes();
    const seconds = today.getSeconds();

    //add '0' to hour, minute & second when they are less 10
    const hour = hours < 10 ? "0" + hours : hours;
    const minute = minutes < 10 ? "0" + minutes : minutes;
    const second = seconds < 10 ? "0" + seconds : seconds;

    //make clock a 12-hour time clock
    const hourTime = hour > 12 ? hour - 12 : hour;

    // if (hour === 0) {
    //   hour = 12;
    // }
    //assigning 'am' or 'pm' to indicate time of the day
    const ampm = hour < 12 ? "AM" : "PM";

    // get date components
    const month = today.getMonth();
    const year = today.getFullYear();
    const day = today.getDate();

    //declaring a list of all months in  a year
    const monthList = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ];

    //get current date and time
    const date = monthList[month] + " " + day + ", " + year;
    const time = hourTime + ":" + minute + ":" + second + ampm;

    //combine current date and time
    const dateTime = date + " - " + time;

    //print current date and time to the DOM
    document.getElementById("date-time").innerHTML = dateTime;
    setTimeout(clock, 1000);
  }
});
Enter fullscreen mode Exit fullscreen mode

Styling Our Clock with CSS

Let's add some CSS styles to our app to make it more attractive.

/*font family from google fonts*/
@import url("https://fonts.googleapis.com/css2?family=Oswald:wght@300;400&display=swap");

html {
  font-size: 62.5%; /*62.5% = 10px; to make it easier to calculate REM units.*/
}
body {
  text-align: center;
  font-family: "Oswald", sans-serif;
  font-weight: 300;
  font-size: 2.2rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #faedcd;
  height: 100vh;
}
#clock {max-width: 600px;}

/* for smaller screens below 700px */
@media only screen and (max-width: 700px) {
  body {font-size: 1.8rem;}
}

/*for smaller screens below 300px*/
@media only screen and (max-width: 300px) {
  body {font-size: 1.6rem;}
}
Enter fullscreen mode Exit fullscreen mode

This is how our digital clock app looks and behaves in the end:

CONCLUSION

I hope you found this tutorial useful. Please leave a comment and feel free to follow me on Twitter if you enjoyed this article.

Top comments (4)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

This is a wonderful explanation of how to approach such a problem.

Nevertheless, one should think about using the Intl.DateTimeFormat Object.

You should also use template strings in the area of string concatenations.

Otherwise you run the risk of transporting old knowledge further and further...

But as I said, still a very good introduction.

Below is an example of how short the topic can be done using the Intl.DateTimeFormat object.

<!DOCTYPE html>
<html lang=en>
  <meta charset=UTF-8>
  <title>Clock</title>
  <style>
    body{
      height:100vh;
      background:silver;
      font-family:monospace;
      font-size: 2vw;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>
  <h1 id=dateTime>clock</h1>
  <script>
    options = {
      year: 'numeric', month: 'long', day: 'numeric',
      hour: 'numeric', minute: 'numeric', second: 'numeric'
    };
    const clock = () => dateTime.innerText=new Intl.DateTimeFormat('en-EN', options).format(new Date())
    clock()
    setInterval(clock, 1000);
  </script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dboatengx profile image
Boateng Dickson

Thanks for the insight. Really appreciate!

Collapse
 
curiousdev profile image
CuriousDev

Thank you for this good example! I like how this can be useful for beginners, because you show how you use HTML to show the clock and to connect everything, JS for the clock to work and finally the optional CSS to design it.

Collapse
 
dboatengx profile image
Boateng Dickson

Iā€™m glad you found it useful.