Thursday, November 17, 2011

How to show a running date and time clock in your website.

Using Ajax, I created a simple script that will show a running date and time clock in the website. Basically, the function will get the actual date and time of the server, then set a time out that loop in every second.

To get the date and time, you can initialize it by Date() object.

var today = new Date();


From there, you can get the date and time, please see below for the object methods that you can call.

var cmonth = today.getMonth(); // this will return the index of the month[0-11]
var cyear = today.getFullYear(); // this will return the year in 4 digits
var cday = today.getDate();
var chour = today.getHours();
var cmin = today.getMinutes();
var csec = today.getSeconds();


As for the complete implementation, please see below.

<html>
<head>
        <title>Hotel Aide</title>
        <script type="text/javascript">
        function updateTime() {
                var today = new Date();
                var month = new Array(12);
                month[0]="Jan";
                month[1]="Feb";
                month[2]="Mar";
                month[3]="Apr";
                month[4]="May";
                month[5]="Jun";
                month[6]="Jul";
                month[7]="Aug";
                month[8]="Sep";
                month[9]="Oct";
                month[10]="Nov";
                month[11]="Dec";

                var cmonth = month[today.getMonth()];
                var cyear = today.getFullYear();
                var cday = today.getDate();
                var chour=today.getHours();
                var cmin=today.getMinutes();
                var csec=today.getSeconds();

                if (chour<10) chour = "0"+chour;
                if (cmin<10) cmin = "0"+cmin;
                if (csec<10) csec = "0"+csec;

                document.getElementById('datetime').innerHTML= cmonth+' '+cday+', '+cyear+' '+chour+':'+cmin+':'+csec;
                window.setTimeout('updateTime();',1000);
        }
        </script>
</head>
<body onLoad="updateTime();">
        <span id="datetime"></span>
</body>
</html>


Hope this is helpful! Thanks!

No comments:

Post a Comment