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
- Other Related Concepts
Explanation:The code may seem intimidating at first, but it’s really 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() object, this object returns the browser’s date along with the time zone. But remember the date object is static, we would have to keep updating it, we will get into the logic behind this later.
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, these values are stored in variables. And lastly, we use a variable session to store the AM or PM tag.
Note: Here date in date.getHours() etc is the variable we used to store the date earlier.
The date.getHours method returns values from 0-23, and given we are programming a 12 hours clock we use the following if statement to set 0 as 12.
And, we use this if to subtract hours greater than 12 and to overwrite the value of session to “PM”.
To understand the next bit of code, you need to be familiar with two concepts. Firstly the getHours(), getMinutes() and getSeconds() methods return value 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.
Using this operator, we solve the above problem by adding a 0 before the digit that is less than 10.
Next, we create a variable time to store the time in the desired format.
Next, to display the time on the webpage we use the following code.
Here, document represents the webpage, the .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 keep it updated. I’ve added the syntax for it below.
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.
And all that’s left is to run the function.