Home Asp.net Display Computer Current Local Time in JavaScript

Display Computer Current Local Time in JavaScript

4
0

In my previous tutorials, I’d explained display your computer local time on webpage using jQuery, how to show alert message from code-behind, how to call javascript function from code-behind and more cracking tutorials on Asp.net, JavaScript and jQuery here.

Now here in this tutorial, I’ll explain how you can show or display computer current local time in javascript without page refresh in your web page of your asp.net website with example demo code.

We can display a clock which will be showing the local time of the client’s computer by using JavaScript.

Note: This time displayed is taken from user computer and not from the server.

Display Computer Current Local Time in JavaScript

Following is the JavaScript function to show current time on webpage like clock:

<script type=”text/javascript”>
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + “/” + dt.getDate() + “/” + dt.getFullYear();
document.getElementById(‘cTime’).innerHTML = cDate + ” – “ + dt.toLocaleTimeString();
window.setTimeout(‘DisplayCurrentTime()’, refresh);
}
</script>

And here is the complete HTML Markup code that I used to display computer current local time in javascript for my .aspx page:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Show/Display Local Computer’s Current time in webpage using
JavaScript </title>
<script type=”text/javascript”>
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + “/” + dt.getDate() + “/” + dt.getFullYear();
document.getElementById(‘cTime’).innerHTML = cDate + ” – “ + dt.toLocaleTimeString();
window.setTimeout(‘DisplayCurrentTime()’, refresh);
}
</script>
</head>
<body onload=”DisplayCurrentTime();”>
<form id=”form1″ runat=”server”>
<h4>
Show/Display Local Computer’s Current time in webpage using JavaScript</h4>
<div>
<asp:Label ID=”cTime” runat=”server” ClientIDMode=”Static” BackColor=”#ffff00″
Font-Bold=”true” />
</div>
</form>
</body>
</html>

As you can see from above sample code, I called DisplayCurrentTime() method on onload event of body tag that loads the current local system time, set the interval for every one seconds and refresh current time without page refresh to display on the webpage. Following is the live demo of the above example code.

Live Demo

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!