Real time changing Clock showing date and time

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.

Here is the demo of this script and code is given below that.

Wed Oct 23 2019 11:09:31 GMT+0600 (Bangladesh Standard Time)

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 x = new Date()
document.getElementById('ct').innerHTML = x;
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 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
Wed, 23 Oct 2019 05:10:20 GMT

Displaying in mm/dd/yy H:m:s format

Here is the code
function display_ct() {
var x = new Date()
var x1=x.getMonth() + 1+ "/" + x.getDate() + "/" + x.getYear(); 
x1 = x1 + " - " +  x.getHours( )+ ":" +  x.getMinutes() + ":" +  x.getSeconds();
document.getElementById('ct').innerHTML = x1;
display_c();
 }
Note that we have only changed the display_ct() function part , other code remains same. Here is the output
10/23/2019 - 11:10:20

To display clock inside a textbox

Create a textbox and give id to it
<input type=text id='t1' size='70'>
For displaying add this line inside the function display_ct()
document.getElementById('t1').value = x;

Changing font size and font color of display

document.getElementById('ct3').style.fontSize='30px';
document.getElementById('ct3').style.color='#0030c0';
document.getElementById('ct3').innerHTML = x2;
10/23/2019 - 11:10:20

Adding 0 to single digit numbers

We can display 5 hours as 05 hours or 2 minutes as 02 minutes.
// date part ///
var month=x.getMonth()+1;
var day=x.getDate();
var year=x.getFullYear();
if (month <10 ){month='0' + month;}
if (day <10 ){day='0' + day;}
var x3= month+'-'+day+'-'+year;

// time part //
var hour=x.getHours();
var minute=x.getMinutes();
var second=x.getSeconds();
if(hour <10 ){hour='0'+hour;}
if(minute <10 ) {minute='0' + minute; }
if(second<10){second='0' + second;}
var x3 = x3 + ' ' +  hour+':'+minute+':'+second

<span id='ct4' style="background-color:#FFFF00"></span>
10-23-2019 11:10:20

0 Comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More