DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Updated on • Originally published at flexiple.com

Programming a JavaScript Clock

In this article, we look at how you can implement a real-time clock in JavaScript. We break down and explain the code so that you can replicate it with ease.

However, in case you are a seasoned programmer and are here only for the code, you can dive straight into the solutions. In case you aren’t, I would recommend you follow along step by step.

Table of Contents

  1. Overview of JavaScript Clock
  2. 12 Hours clock using JavaScript
  3. 24 Hour clock using JavaScript

Overview of JavaScript Clock:

Clocks are of utmost importance on websites where time plays a large factor, e.g: booking websites, e-commerce, etc.

However, given JavaScript supports and lets us manipulate web pages in real-time, building clocks that show the current time in JavaScript has become quite straightforward.

Note: In this article, we look closely at the JavaScript code behind a clock. We do not talk about CSS styling as there are plenty of blogs already available that brief about it. We rather focus largely on the JavaScript code.

12 Hours clock using Javascript

As the name suggests, in this section we look at how to build a 12 hours JavaScript clock.

Javascript Clock Code (12 hours):

Explanation:

The above code may seem intimidating at first, but it’s quite straightforward once you break it down.

We start the code by defining a function, currentTime(). Inside the function, we store the current time in a variable called date.

We do that by using the new Date() constructor, this constructor returns the browser’s date along with the time zone.

Note: The date object is static, we would have to keep updating it, we do that later in the code.

let date = new Date(); 
Enter fullscreen mode Exit fullscreen mode

Once this is done, we extract the hours, minutes, and seconds from the variable (date) using the getHours(), getMinutes() and getSeconds() methods.

These methods return the respective values when a date is passed, we store them in different variables.

And lastly, we use a variable called "session" to store the AM or PM tag.

let hh = date.getHours();
let mm = date.getMinutes();
let ss = date.getSeconds();
let session = "AM";
Enter fullscreen mode Exit fullscreen mode

Note: Here date in date.getHours(), etc, is the variable we used to store the current date earlier.

The date.getHours method returns values between 0-23, and given we are programming a 12 hours clock we use the following if statement to reset 12 to 0.

if(hh == 0){
      hh = 12;
  }
Enter fullscreen mode Exit fullscreen mode

And, we use another if to subtract hours greater than 12 and to assign the value of the session variable to “PM”.

if(hh > 12){
    hh = hh - 12;
    session = "PM";
}
Enter fullscreen mode Exit fullscreen mode

To understand the next bit of code, you need to be familiar with two concepts.

Firstly, the getHours(), getMinutes() and getSeconds() methods return values between 0 to 23, 59, 59 respectively. The key point here is that single digit values are returned as # (eg: 7), however, in our clock, these values need to be displayed as ## (eg: 07).

And to achieve this we use ternary operators. This operator returns a value if the condition is true and another value if it is false. I’ve added the syntax below.

(condition ? if true : if false);
Enter fullscreen mode Exit fullscreen mode

Using this operator, we solve the above problem by adding a 0 before the digit that is less than 10.

hh = (hh < 10) ? "0" + hh : hh;
mm = (mm < 10) ? "0" + mm : mm;
ss = (ss < 10) ? "0" + ss : ss;
Enter fullscreen mode Exit fullscreen mode

Next, we create a variable time to store the time in the desired format.

let time = hh + ":" + mm + ":" + ss + " " + session;
Enter fullscreen mode Exit fullscreen mode

To display the time we use the following code.

document.getElementById("clock").innerText = time 
Enter fullscreen mode Exit fullscreen mode

Here, document represents the webpage, .getElementbyId() returns the element whose ID has been passed as the parameter in our case “clock”. And the innertext property sets the context of the node to time.

And lastly, the most important part, remember I mentioned that get date() returns a static value. We use the setTimeout() method to update it. I’ve added the syntax for it below.

setTimeout(function, milliseconds, param1, param2, ...)
Enter fullscreen mode Exit fullscreen mode

This method calls or runs a function after a specified number of milliseconds. Note: 1000ms = 1 second.

We use this method to update the code every second, to keep our clock running.

let t = setTimeout(function(){ currentTime() }, 1000);
Enter fullscreen mode Exit fullscreen mode

And all that’s left is to run the function.

currentTime(); 
Enter fullscreen mode Exit fullscreen mode

24 Hour clock - Code & Explanation

The code for a 24-hour clock is quite similar to the previous code, we only have one major change.

Explanation:

The only difference here is that we have removed the first if statement, which changed 0 to 12, and in the second if we have removed the condition to subtract hours by 12.

Do let me know your thoughts/ queries in the comments below.

Top comments (0)