DEV Community

Cover image for Create a Digital Clock using JavaScript
Fahad Hassan
Fahad Hassan

Posted on

Create a Digital Clock using JavaScript

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

Let's Get started!

JavaScript Code

JavaScript code includes 3 main code sections

  • tick() function
  • getDayName() function
  • setInterval() Method

1. tick() function :

const tick = () =>{ /*entire code of clock*/ }
Enter fullscreen mode Exit fullscreen mode

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

const current = new Date();
Enter fullscreen mode Exit fullscreen mode

Date object contains different built-in javascript methods Date object methods

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

const current = new Date();

    let ss =current.getSeconds();
    let mm = current.getMinutes()
    let hh = current.getHours();
    let currentDay = current.getDay();

Enter fullscreen mode Exit fullscreen mode

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'

const meridiem = 'AM';
Enter fullscreen mode Exit fullscreen mode

After this, we have to set some conditions on current hours
to display time in 12-hour format.

    if(hh === 00){
        hh = 12
        meridiem = 'AM';
    }
    else if( hh === 12 ){
        meridiem = 'PM';
    }
    else if( hh > 12){
        hh = hh - 12
        meridiem = 'PM';
    }
Enter fullscreen mode Exit fullscreen mode

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.

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.

    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();
Enter fullscreen mode Exit fullscreen mode

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()

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

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 :

setInterval(function_name,time_interval);
Enter fullscreen mode Exit fullscreen mode

Now to execute our function on every clock second we will use setInterval() method as follows.

setInterval(tick,1000)
Enter fullscreen mode Exit fullscreen mode

Now let's arrange the complete code

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)

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Using JavaScript's in-built date and time formatting functionality would probably be an easier way to go. Also easier to internationalise

Collapse
 
fahadhassan1213 profile image
Fahad Hassan

genuinely thanks for taking the time to comment.
I will definitely try to improve this to make it better