Digital Clock using JavaScript

nehasoni__

Neha Soni

Posted on May 15, 2021

Digital Clock using JavaScript

Hello readers,

In this article, you will learn how to design a simple animated Digital Clock in JavaScript. A digital clock or watch in which the hours, minutes, and sometimes seconds are indicated by digits, as opposed to an analog clock, where the time is indicated by the positions of rotating hands.

Let's get started

Prerequisite

  • Basic knowledge of HTML
  • Basic knowledge of CSS
  • Basic knowledge of JavaScript

It's Time to Code!

To create a digital clock first, you need to create three files one HTML File(index.html), the second one is CSS file(style.css) and the third one is JS file(index.js).

HTML code

index.html



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Digital Clock</title>
    <link rel="stylesheet" href="style.css">
  </head>
    <body>
        <!--Display day information e.g Wednesday March 12,2021-->
        <div id="dayIntro">
            <p id="dayName"></p>
        </div>
        <div class="container">
            <!-- Display time -->
            <div class="dispClock">
                <div id="time"></div>
            </div>
        </div>
        <script src="index.js"></script>
    </body>
</html>


Enter fullscreen mode Exit fullscreen mode

CSS Code

style.css



/* Google font */
@import url('https://fonts.googleapis.com/css?family=Orbitron');

*{
    margin: 0;
    padding: 0;

  }
  html,body{
    display: grid;
    place-items: center;

  }
  #dayIntro
{
    font-size: 40px;
    font-weight: 600;
    letter-spacing: 3px;
    border: 7px solid rgb(17,129,134);
    border-radius: 10px;
    margin: 20px;
    font-family: 'Times New Roman', Times, serif;
    padding: 15px;
    background: linear-gradient(180deg, #a8b9d3,rgb(173, 227, 229));
}
  .container{
    height: 120px;
    width: 550px;
    position: relative;
    background: linear-gradient(135deg, #14ffe9, #ffeb3b, #ff00e0);
    border-radius: 10px;
    cursor: default;

  }
  .container .dispClock,
  .container {
    position: absolute;
    top: 28%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .container .dispClock{
    top: 50%;
    height: 105px;
    width: 535px;
    background: linear-gradient(147deg, #000000 0%, #2c3e50 74%);
    border-radius: 6px;
    text-align: center;
  }
  .dispClock #time{
    line-height: 85px;
    color: #fff;
    font-size: 70px;
    font-weight: 600;
    letter-spacing: 1px;
    font-family: 'Orbitron', sans-serif;
    background: linear-gradient(135deg, #14ffe9, #ffeb3b, #ff00e0);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;

  }


Enter fullscreen mode Exit fullscreen mode

JavaScript Code

Now here comes the main part. The entire code for the working of the clock is written within the currentTime() function.

Let's discuss everything step by step:-

Step 1:- Create a function currentTime().



function currentTime()
{
  //code to be executed
}


Enter fullscreen mode Exit fullscreen mode

Step 2:- Inside the function, create an object of Date Class which allows you to call day, year, month, day, hour, minute, second, etc.



function currentTime()
{
    const clock = document.getElementById("time")
    const dayIntro=document.getElementById("dayName");

    let time = new Date();        // creating object of Date class
    let dayName=time.getDay();
    let month=time.getMonth();
    let year=time.getFullYear();
    let date=time.getDate();
    let hour = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();
}


Enter fullscreen mode Exit fullscreen mode

Step 3:- The Date object works on the 24-hour format so we change the hour back to 1 when it gets larger than 12. The AM/PM also changes according to that.



var am_pm = "AM";
   if(hour==12)
   am_pm = "PM";

   if (hour > 12) 
   {
     hour -= 12;
     am_pm = "PM";
   }
   if (hour == 0) 
   {
     hour = 12;
     am_pm = "AM";
   }


Enter fullscreen mode Exit fullscreen mode

Step 4:- The obtained hours, minutes, and seconds from Date object will be displayed in single-digit if less than 10. To display the elements of time in two-digit format, a 0 is appended before them whenever they are less than 10.



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


Enter fullscreen mode Exit fullscreen mode

Step 5:- Now once our time is ready, make a string using the same HH: MM: SS format changing the hour, minute, and a second value with the values, we get from Date object methods.



//value of current time
let currentTime = hour + ":" + min + ":" + sec +" "+ am_pm;

// value of present day(Day, Month, Year)
var months=["January","February","March","April","May","June","July","August","September","October","November","December"];
var week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

var presentDay=week[dayName]+", "+months[month]+" "+date+", "+year;


Enter fullscreen mode Exit fullscreen mode

Step 6:- Once the string is ready, let's display it in the div which we made before. This is done by obtaining the div using the document.getElementById method and give our time as the content of the div using the innerHTML property.



const clock = document.getElementById("time");
const dayIntro=document.getElementById("dayName");

clock.innerHTML = currentTime;
dayIntro.innerHTML = presentDay;


Enter fullscreen mode Exit fullscreen mode

Step 7:- To call the function every second use setInterval() method and set the time-interval as 1000ms which is equal to 1s.(Call setInterval() method outside the function).



setInterval(currentTime, 1000);


Enter fullscreen mode Exit fullscreen mode

Step 8:- Call the function currentTime() at the end to start function at exact reloading of page.



currentTime();  //calling currentTime() function to initiate the process 


Enter fullscreen mode Exit fullscreen mode

Complete javascript code

index.js



setInterval(currentTime, 1000);

function currentTime()
{
    let time = new Date();   // creating object of Date class
    let dayName=time.getDay();
    let month=time.getMonth();
    let year=time.getFullYear();
    let date=time.getDate();
    let hour = time.getHours();
    let min = time.getMinutes();
    let sec = time.getSeconds();

    var am_pm = "AM";
    if(hour==12)
    am_pm = "PM";
    if (hour > 12) {
    hour -= 12;
    am_pm = "PM";
    }
    if (hour == 0) {
    hour = 12;
    am_pm = "AM";
    }

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

   //value of current time
   let currentTime = hour + ":" + min + ":" + sec +" "+ am_pm;

  // value of present day(Day, Month, Year)
  var months=["January","February","March","April","May","June","July","August","September","October","November","December"];
  var week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

  var presentDay=week[dayName]+", "+months[month]+" "+date+", "+year;

  const clock = document.getElementById("time");
  const dayIntro=document.getElementById("dayName");

  clock.innerHTML = currentTime;
  dayIntro.innerHTML = presentDay;
}

currentTime();  //calling currentTime() function to initiate the process 


Enter fullscreen mode Exit fullscreen mode

congrats.gif
You have just created a digital clock. It will look something like this!.
Demo

If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝

Thanks for reading 😃

I would ❤ to connect with you at Twitter | LinkedIn | GitHub

Let me know in the comment section if you have any doubt or feedback.

You should definitely check out my other Blogs:

See you in my next Blog article, Take care!!

Happy Learning😃😃

💖 💪 🙅 🚩
nehasoni__
Neha Soni

Posted on May 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related