Create a digital clock

Problem Statement -

Create a digital clock that shows the current time in HH:MM:SS format.

Example

10:57:23

10:57:24

10:57:25

10:57:26

10:57:27

The date function returns a single moment in time in a platform-independent format. There are different methods available with the Date function which we will be using to create our clock.

  • getHours() - This method returns the hours of date in 24hrs number format like (0 – 23).

  • getMinutes() - This will return the minutes of the hours in number format like from (0 – 59).

  • getSeconds() - This method returns the seconds of the minutes in number format like (0 – 59).

  • getMilliseconds() - This method returns the milliseconds of the seconds in number format like (0 – 999).

    We will create a function which will be using these methods to get the current time in HH:MM:SS format.

      const clock = () => {
          const time = new Date(),
          hours = time.getHours(),
          minutes = time.getMinutes(),
          seconds = time.getSeconds();
        return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
      }
    

    We are using this pad() helper function which will format the input by appending 0 if the number is a single digit.

      const pad = (inp) => {
        return String(inp).length == 1 ? '0' + inp : inp;
      };
    

    Now when we call the clock function it will return the single instance of time at the moment it was called.

      console.log(clock());
      //10:59:23
    

    But to make it work like a clock we will need to call this function repeatedly after 1 second. For this we will use the setInterval function which repeatedly calls the function after a given interval of time.

setInterval(function() {
  console.log(clock());
}, 1000);
//10:59:23
//10:59:24
//10:59:25
//10:59:26

Happy Learning!!!.