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.
Display Computer Current Local Time in JavaScript
Following is the JavaScript function to show current time on webpage like clock:
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:
<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.