Learn to create a digital clock in JavaScript and HTML. Follow our step-by-step guide to building a simple clock in 12 and 24-hour formats.
In this article, we will discuss how to implement a Clock in Javascript. We will first implement a 24-hour clock. Then, we will provide a way to switch formats between 12- and 24-hour formats.
How to build a clock in Javascript? (24-hour format)
First, we want to arrange the contents of our HTML page. It is going to be a simple page with a single div
tag that will contain the clock. The HTML code is shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Clock</title>
</head>
<body>
<div id="time">8:10:45</div>
</body>
</html>
The title has been set to Javascript Clock
, and the body
contains the clock within a div
tag. Next, we want to implement the Javascript code that will get the current time and update the div
tag with the current time. To do this within Javascript, we will need a way to
- Get the current time
- Repeatedly update the current time on the
div
after a fixed duration, say every 1 second
Step 1: Get the current time for the clock in javascript
We will now implement the updateTime()
function within the script
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Clock</title>
</head>
<body>
<div id="time">8:10:45</div>
<script>
function updateTime() {
// get the current date
let now = new Date();
// extract the hours minutes and seconds data from the current date
// then format as two digits with leading zeros if less than two digits
let hour = now.getHours().toString().padStart(2, "0");
let min = now.getMinutes().toString().padStart(2, "0");
let sec = now.getSeconds().toString().padStart(2, "0");
// arrange the hour minute second info like hour:min:sec
let timeNow = `${hour}:${min}:${sec}`;
// finally, update the div element in the HTML
document.getElementById("time").innerHTML = timeNow;
}
</script>
</body>
</html>
The code is straightforward and self-explanatory.
After getting the time information and formatting it as a display string, we set the div
element in the document tree to the formatted time.
Step 2: Repeatedly updating the clock time
Next, we want to look for a way to call updateTime()
at every fixed interval, say every 1 second.
To do this in Javascript, we need to make use of the setInterval() function. setInterval()
will need two inputs;
- The
updateTime
function - The intervals are in milliseconds. Here we will set it to 1000 milliseconds (= 1 second)
We can now modify the code by adding a call to setInterval
in our Javascript as follows;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Clock</title>
</head>
<body>
<div id="time">8:10:45</div>
<script>
// call updateTime every 1 second / 1000 milliseconds
setInterval(updateTime, 1000);
function updateTime() {
// get the current date
let now = new Date();
// extract the hours minutes and seconds data from the current date
// then format as two digits with leading zeros if less than two digits
let hour = now.getHours().toString().padStart(2, "0");
let min = now.getMinutes().toString().padStart(2, "0");
let sec = now.getSeconds().toString().padStart(2, "0");
// arrange the hour minute second info like hour:min:sec
let timeNow = `${hour}:${min}:${sec}`;
// finally, update the div element in the HTML
document.getElementById("time").innerHTML = timeNow;
}
updateTime();
</script>
</body>
</html>
Notice that we had to make a call to updateTime()
so that the time is rendered when the HTML is initially loaded. Then, after every 1 second, setInterval()
updates the div
element with the current time.
We can now view our code in the browser.
Step 3: Create the ability to switch to a 12-hour format
We have made some modifications to the HTML. We added a check box so that we can switch between 12-hour and 24-hour time formats. Our javascript code can now help us determine if we want a 12- or 24-hour display. Below is the modified code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Clock</title>
<style>
body {
margin-top: 10%;
margin-left: 10%;
padding: 5;
font-family: Arial, Helvetica, sans-serif;
}
#time {
font-size: 60px;
}
</style>
</head>
<body>
<div id="time">8:10:45</div>
<input type="checkbox" id="time_format">
<script>
// call updateTime every 1 second / 1000 milliseconds
setInterval(updateTime, 1000);
function updateTime() {
// get the current date
let now = new Date();
// extract the hours minutes and seconds data from the current date
// then format as two digits with leading zeros if less than two digits
let hour = now.getHours()
let min = now.getMinutes()
let sec = now.getSeconds()
// check and return the correct format
let checkbox = document.getElementById("time_format");
let timeNow; // will store the hour, minute, second info like hour:min:sec
if (checkbox.checked == true) {
// 12 hour format
timeNow = get_12hr_format(hour, min, sec);
} else {
// 24 hour format
timeNow = `${toTwoDigits(hour)}:${toTwoDigits(min)}:${toTwoDigits(sec)}`;
}
// finally, update the div element in the HTML
document.getElementById("time").innerHTML = timeNow;
};
function get_12hr_format(hour, min, sec) {
// get the 12 hour format for the hour
let h = (hour % 12 == 0) ? 12 : (hour % 12);
// get the meridiem
let meridiem = (Math.trunc(hour / 12) == 0) ? "AM" : "PM";
// return the final 12 hour formatted time
return `${toTwoDigits(h)}:${toTwoDigits(min)}:${toTwoDigits(sec)}${meridiem}`;
}
function toTwoDigits(num) {
// format the hour, min and seconds as two digits with
// leading zeros if less than two digits
return num.toString().padStart(2, "0");
}
updateTime();
</script>
</body>
</html>
Our clock is now ready! We can now use the checkbox to activate/deactivate 12-hour format in our clock.
Conclusion
That’s it for our short tutorial on “how to build a clock in javascript”. We discussed how to make the clock display in both 12-hour and 24-hour formats. If you liked this tutorial, feel free to check out our website for more Javascript tips and tutorials!