How to create a clock in JavaScript?
We create an instance of date object to use the method of date object.
Create Date object:
var date=new Date()
Methods of date objet: There are following methods of the date object.
getDate(): It returns the day of the month
getDay(): It returns the day of the week
getSeconds(): It returns the seconds
getMinutes(): It returns the minutes
getHours(): It returns the hour start from 0 to 23
getTime(): It returns the complete time
Example: In this example I am using some methods of data object to access the time.
<html>
<head><title>ShowClock</title>
<script type="text/javascript">
function ShowTime()
{
var time=new Date()
var h=time.getHours()
var m=time.getMinutes()
var s=time.getSeconds()
// add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('txt').value=h+" : "+m+" : "+s
t=setTimeout('ShowTime()',1000)
}
function checkTime(i)
{
if (i<10)
{
i="0" + i
}
return i
}
</script>
</head>
<body bgcolor="#ccccff">
<input type="button" value="Show Clock!" onClick="ShowTime()">
<font color="olive">
(Please click on this button)
</font><br /><br />
<input type="text" id="txt">
</body>
</html>
Output: When you click on "Show Clock" button then clock will display in the given textbox (see the following figure).
Figure : Display a Clock in textbox.