We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.
We have seen in our date object example how to display current date and time where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using setTimeout function. This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.
Here is the demo of this script and code is given below that.
Sat Apr 23 2016 08:27:22 GMT+0530 (IST)
Here is the code
<html>
Let us start with using UTC string
function display_ct() {
The output is here
Sat, 23 Apr 2016 02:57:22 GMT
function display_ct() {
Note that we have only changed the display_ct() function part , other code remains same. Here is the output
3/23/2016 - 8:27:22
document.getElementById('ct3').style.fontSize='30px';
Here is the demo of this script and code is given below that.
Sat Apr 23 2016 08:27:22 GMT+0530 (IST)
Here is the code
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
</script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
Changing the display format
To change the display format we need to change the function part only where we can change the display part.Let us start with using UTC string
function display_ct() {
var strcount
var x = new Date()
var x1=x.toUTCString();// changing the display to UTC string
document.getElementById('ct').innerHTML = x1;
tt=display_c();
}
The output is here Sat, 23 Apr 2016 02:57:22 GMT
Displaying in mm/dd/yy H:m:s format
Here is the code
function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + x.getSeconds();
document.getElementById('ct').innerHTML = x1;
tt=display_c();
}
Note that we have only changed the display_ct() function part , other code remains same. Here is the output3/23/2016 - 8:27:22
Comments
Post a Comment