Here I have defined a Date object with the new keyword, new Date() to define the date object and extracted Hours, Minutes and Seconds using functions getHours(), getMinutes() and getSeconds() respectively and given codes for a simple clock having 24 hours format and a clock along with AM or PM.
Table of Contents
JavaScript code for creating a simple digital clock
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds(
//to add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('clock').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()', 500)
}
function checkTime(i)
{
if (i<10)
{ i="0" + i}
return i
}
window.onload=startTime;
</script>
<div id="clock" style="font-size:35px;color:#00aaff;text-shadow:2px 2px 2px blue;
border:3px groove blue;background-color:#aaffaa; width:195px; height:40px"></div>
checkTime() function is used here to add zero in front of numbers less then 10 and executed the function ‘startTime()’ using window.onload.
Here is an inline CSS code to design the clock, you can change its values according to your wish. If you want to use the CSS in separate CSS files and link to your web page, you can write the CSS as follows on a distinct CSS file.
#clock{
font-size:35px;
color:#00aaff;
text-shadow:2px 2px 2px blue;
border:3px groove blue;
background-color:#aaffaa;
width:195px;
height:40px;
}
JavaScript code for creating a digital clock with AM or PM
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
var ap="AM";
//to add AM or PM after time
if(h>11) ap="PM";
if(h>12) h=h-12;
if(h==0) h=12;
//to add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('clock').innerHTML=h+":"+m+":"+s+" "+ap
t=setTimeout('startTime()', 500)
}
function checkTime(i)
{
if (i<10)
{ i="0" + i}
return i
}
window.onload=startTime;
</script>
<div id="clock" style="font-size:35px;color:#00aaff;text-shadow:2px 2px 2px blue;
border:3px groove blue;background-color:#aaffaa; width:195px;"></div>
In the above code, variable ap is added to make the clock 12-hour format and to add “AM” or “PM” after the time and added this variable at the innerHTML of the clock element.
Preview of digital clock created with JavaScript
Read Next: How To Handle Drag and Drop Event In JavaScript
Comments are closed.