Digital Clock using JavaScript
Tags: javascript, html, css, webdev
Published: 2021-05-15 06:31:52

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
```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>
``` 
### CSS Code
style.css
```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;
   
  }
```
### 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:-*<br>
**Step 1:-** Create a function *currentTime()*.
```js
function currentTime()
{
  //code to be executed
}
```
**Step 2:-** Inside the function, create an object of *Date Class* which allows you to call day, year, month, day, hour, minute, second, etc.
```js
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();
}
```
**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.
```js
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";
   }
```
**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.
```js
 hour = hour < 10 ? "0" + hour : hour;
 min = min < 10 ? "0" + min : min;
 sec = sec < 10 ? "0" + sec : sec;
```
**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.
```js
//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;
```
**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.
```js
const clock = document.getElementById("time");
const dayIntro=document.getElementById("dayName");

clock.innerHTML = currentTime;
dayIntro.innerHTML = presentDay;
```
 **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).
```js
setInterval(currentTime, 1000);
```
**Step 8:-** Call the function **currentTime()** at the end to start function at exact reloading of page.
```js
currentTime();  //calling currentTime() function to initiate the process 
```
**Complete javascript code**<br>
index.js
```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 
```

![congrats.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1619869148054/jXvcfAwxK.gif)
**You have just created a digital clock. It will look something like this!**.
![Demo](https://camo.githubusercontent.com/93fc5cec53819c8c55029bdf4ebf16b39425df0c1a1862b8f1b82f574b210e79/68747470733a2f2f696d322e657a6769662e636f6d2f746d702f657a6769662d322d6161386631316337633530632e676966)

- [Live Demo](https://nehasoni05.github.io/Digital_Clock/index.html) 
- You can find the code at my  [GitHub Repository](https://github.com/nehasoni05/Digital_Clock) 

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](https://twitter.com/nehasoni__)  |  [LinkedIn](https://www.linkedin.com/in/neha-soni-70a6231b1/) | [GitHub](https://github.com/nehasoni05)

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

**You should definitely check out my other Blogs:**
-  [Introduction to JavaScript: Basics](https://nehasoni.hashnode.dev/introduction-to-javascript-basics) 
-  [Playing with JavaScript Objects](https://nehasoni.hashnode.dev/playing-with-javascript-objects-1) 
- [7 JavaScript Data Structures you must know](https://nehasoni.hashnode.dev/7-javascript-data-structures-you-must-know)
-  [Git & Github: All you need to know](https://nehasoni.hashnode.dev/git-and-github-all-you-need-to-know) 
-  [Introduction to ReactJS
](https://nehasoni.hashnode.dev/introduction-to-reactjs) 

See you in my next Blog article, Take care!!<br>
**Happy Learning😃😃**