Finding date and time - A simple clock in JavaScript
Sponsored Links
It is easy to find the time and date on the visitor's computer (client side) using the JavaScript Date object with its various methods. Let's construct a simple function that finds the time (hours:minutes:seconds) and prints it in the document.
<script type="text/javascript">
<!--
function det_time()
{
var d = new Date();
var c_hour = d.getHours();
var c_min = d.getMinutes();
var c_sec = d.getSeconds();
var t = c_hour + ":" + c_min + ":" + c_sec;
return t;
}
//-->
</script>
When we call this function it prints the time as follows:
In order to keep the clock ticking, as it were, we would have to call det_time() function again and again. JavaScript provides an method called setInterval() that takes two arguments; the first is the function that has to be called repeatedly and the second, the time interval (in milliseconds). In our case, the clock has to be called every second (1000 milliseconds).
setInterval("det_time()", 1000);
Lastly, for correct execution, its best to put this clock inside a text field.
Here is the complete code:
//This function is placed in the HTML head section
function det_time()
{
var d = new Date();
var c_hour = d.getHours();
var c_min = d.getMinutes();
var c_sec = d.getSeconds();
var t = c_hour + ":" + c_min + ":" + c_sec;
document.myform.my_time.value = t;
}
//The following code is placed in the HTML body...
<form name="myform">
<input type="text" size="10" maxlength="10" value=""
name="my_time">
</form>
<script type="text/javascript">
<!--
setInterval("det_time()", 1000);
//-->
</script>
Page contents: Learn how to display date and time on a visitors browser using JavaScript code and thus create a simple JavaScript clock with the setinterval javascript method.
Comments, questions, feedback... whatever!
Recent Articles
Recent Blog Posts
Popular Articles
- Hotmail Sign In page
- Create a Hotmail account - Instructions
- Create Gmail address
- Download and install Outlook Express
- Get your free Gmail address
- Outlook Express new version
- Create my own email address
- Browers for Windows list
- Get email address
- Color combinations for web sites and pages
- Create Yahoo ID
More web tips & tricks
- Outlook Express Help - tips & tricks (53)
- Windows Live Mail help and tips (36)
- Windows Mail help (25)
- Hotmail help and tips (42)
- Yahoo help & support (45)
- AOL email help (26)
- Gmail help and tips (36)
- Internet tips & tricks (12)
- Web Design tips & tricks (33)
- HTML, Javascript tips tricks (68)
- Web Promotion tips & tricks (8)
- Graphics tips & tricks (20)
