Create a simple digital Clock using JavaScript with 12 hr time format

Create a simple digital Clock using JavaScript with 12 hr time format

How to Create a simple Digital Clock using JavaScript with 12 hr time format

In this example we will use two files timer.html and timer.js file to display digital clock in JavaScript in 12hr format. If you want to use it for 24 hr that can also be done with just small change explained in code and example below.

To start with create one .html file with code below. I have named it timer.html however you can use any other name. Once created insert below .html code on that file and save. You need to include .js file on head tag which we will use to display the current time “<script src=”timer.js”></script>“. You can also add .css to beautify the display of clock.

Once done create timer.js file and include that in your .html page as described above. Please use below code to display the time.

In below code window.onload event handler executes the currentTime JavaScript function. Inside the currentTime JavaScript function, first the current date is determined using the JavaScript Date object. Then Hours, Minutes and Seconds are calculated using the getHours, getMinutes and getSeconds function of the JavaScript Date object.

While calculating the Hours, Minutes and Seconds, if the value of Hour, Minute or Second is less than 10 then a Zero is padded in order to make the value in two digits using singleDigit function.

To convert 24 hours to 12 hours we are using clockHr function var hours = clockHr(date.getHours())if you want to display only 24 hour time then remove clockHr and use only var hours = singleDigit(date.getHours()) to display clock. As described above singleDigit function will add 0 if hour is less then 10 and will display it in two digits.

var $ = function(id) { return document.getElementById(id); }; // function to initialise getElementById and use it with $ on script.