Create a Digital Clock using JavaScript 
Tags: javascript, html, css
Published: 2021-05-06 19:08:27

## What we are covering in this article?

In this article, you will learn to create a digital clock in 12-hours format HH: MM: SS AM/PM. As well as we also cover how to display the current day and current date by using some built-in methods of JavaScript.

To get the complete code visit: [GitHub](https://github.com/fahadhassan1213/Digital-Clock)

Let's Get started!

### JavaScript Code

JavaScript code includes 3 main code sections
- `tick()` function
- `getDayName()` function
- `setInterval()` Method

###1. `tick()` function :
```js
const tick = () =>{ /*entire code of clock*/ }
```

Our entire code for displaying the current time will be in the `tick()` function

In this function, we have 2 tasks to do

#### Task# 1

first we have to creat a `new Date()` object
```js
const current = new Date();
```
Date object contains different built-in javascript methods [Date object methods](https://www.w3schools.com/js/js_date_methods.asp)

We want to display the current time which includes (hours, minutes, seconds).We use `getHours()`, `getMinutes()`, `getSeconds()` to display current hours, minutes and seconds

- _**getHours():**_ method returns the hours of the Date as a number (from 0 to 23).
- _**getMinutes():**_ method returns the minutes of the Date as a number (from 0 to 59).
- _**getHours():**_ method returns the seconds of the Date as a number (from 0 to 59).

As we also want to display the current day, then we will use the `getDay()` method to get the current day.

- _**getDay():**_ method returns the weekday of the date as a number (from 0 to 6).

Now let's write some code
```js
const current = new Date();
    
    let ss =current.getSeconds();
    let mm = current.getMinutes()
    let hh = current.getHours();
    let currentDay = current.getDay();

```

As you know, we are creating a digital clock in a 12-hours. format. A 12-hour digital clock includes meridiem (AM/PM). So we need to add meridiem with the time.

initially we will set meridiem to 'AM'
```js
const meridiem = 'AM';
```
After this, we have to set some conditions on current _**hours**_
to display time in 12-hour format.

```js
    if(hh === 00){
        hh = 12
        meridiem = 'AM';
    }
    else if( hh === 12 ){
        meridiem = 'PM';
    }
    else if( hh > 12){
        hh = hh - 12
        meridiem = 'PM';
    }
```
our Task# 1 is completed!. Now moving on to a new task

#### Task# 2

In this task, we need to render our current time on the screen.
To do this we will change the `textContent` of our elements which we defined in our HTML file.

_**Note:**_ to get HTML and CSS files please visit [GitHub/Digital-clock](https://github.com/fahadhassan1213/Digital-Clock).

before rendering the time we need to ensure one thing, that time must be displayed in 2-digits format, when it will be less than 10.  
**Example:** 
If hours = 2 which is less than 10 that means it must be displayed as 02. 
The same will be the case with minutes and seconds.  

```js
    hours.textContent = `${hh<10? `0${hh}`:hh}`;
    minutes.textContent =`${mm<10? `0${mm}`:mm}`;
    seconds.textContent =`${ss<10? `0${ss}`:ss}`
    checkMeridiem.textContent = meridiem;
    date.textContent = current.toLocaleDateString();
```
In the above code, we have a new method `toLocaleDateString()` which will return the current date in _D/M/YYYY_ format

As I mentioned above, we also need to display the current weekday of the current date.

### 2. `getDayName()` function :

We need to define a function called `getDayName()`

```js
const getDayName = (value) =>{
    const DayNames = [
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
    ]
    return DayNames[value];
}
``` 
this function will get an argument named as _value_ which will be an integer value. Inside this function, we have to define an array of names of days of a week and this function will return the day_name corresponding to the argument passed to the function.


### 3. `setInterval()` Method

Now our last task is to continuously call our `tick()` function because we want to increment our time on every clock second.

To do this we have to use a build-in JavaScript method named `setInterval()` which executes a function at specified intervals in milliseconds.

_setInterval_ method gets two arguments. One is function_name and the other is time in milliseconds(1000 milliseconds = 1 second).

#### Syntax of setInterval Method :

```js
setInterval(function_name,time_interval);
```
Now to execute our function on every clock second we will use `setInterval()` method as follows.

```js
setInterval(tick,1000)
```

Now let's arrange the complete code

```js
const tick = () =>{
    const current = new Date();
    
    let ss =current.getSeconds();
    let mm = current.getMinutes()
    let hh = current.getHours();
    let meridiem = 'AM';
    let currentDay = current.getDay();


    //Converting the 24 hours formate into 12 hour formate 
    if(hh === 00){
        hh = 12
        meridiem = 'AM';
    }
    else if( hh === 12 ){
        meridiem = 'PM';
    }
    else if( hh > 12){
        hh = hh - 12
        meridiem = 'PM';
    }


    
    hours.textContent = `${hh<10? `0${hh}`:hh}`;
    minutes.textContent =`${mm<10? `0${mm}`:mm}`;
    seconds.textContent =`${ss<10? `0${ss}`:ss}`
    checkMeridiem.textContent = meridiem;
    date.textContent = current.toLocaleDateString();
    day.textContent = getDayName(currentDay);
    
}

const getDayName = (value) =>{
    const DayNames = [
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
    ]
    return DayNames[value];
}


setInterval(tick,1000)

```

**Hurry!** Our stunning Digital Clock is ready.

Add this to your project showcase and share it with your friends and give a boost to your profile.