Thursday, August 4, 2011

Show server time in client application

Sometime client requirement is to show server time in client application, There are two options to complete this task.
1) Read server Date and Time and do postback with timer.
2) Read Server Date and Time and use Javascript to maintain right date and time.

Expamle:

<script type="text/javascript">
var currenttime = '<%#Session["ServerDateTime"]%>';
var montharray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
var serverdate = new Date(currenttime)

function padlength(what) {
var output = (what.toString().length == 1) ? "0" + what : what
return output
}

function displaytime() {
serverdate.setSeconds(serverdate.getSeconds() + 1)
var datestring = montharray[serverdate.getMonth()] + " " + padlength(serverdate.getDate()) + ", " + serverdate.getFullYear()
var timestring = padlength(serverdate.getHours()) + ":" + padlength(serverdate.getMinutes()) + ":" + padlength(serverdate.getSeconds())
document.getElementById("servertime").innerHTML = datestring + " " + timestring
}

window.onload = function () {
setInterval("displaytime()", 1000)
}

</script>

No comments: