Active Server Pages Programming (ASP)/ASP and Time
Expert: Srini Nagarajan - 11/13/2005
Question-------------------------
Followup To
Question -
Hi,
Is there a way to display current time at the server (second by second)without refreshing the page, using ASP/MSSQL or ASP/VBScript(or javascript). I downloaded a javascript code that shows live time but it takes time from the users computer.
Answer -
Hi
Here is the simple code
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var timerID = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
clearTimeout(timerID);
timerRunning = false;
}
function showtime () {
var thisdate = new Date("<%= Now()%>");
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12 :hours)
if (timeValue == "0") timeValue = 12;
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
function startclock() {
stopclock();
showtime();
}
</SCRIPT>
<BODY onLoad="startclock()">
<CENTER>
<FORM name="clock">
<input type="text" name="face" size=13 value="">
</FORM>
</CENTER>
<p><center>
some text here
</center><p>
Happy Programming!!
-Srini
======================================================================
Hello and thanks for your previous answer
Your code does not work and it shows nothing in input box, but when I changed
var hour = now.gethour(); // to
var hour = thisdate.gethour(); // and similarly for minutes and seconds like
var minute = thisdate.getminute(); // and
var seconds = thisdate.getseconds(); // then
it shows current time, but the seconds are still static i.e. the clock does not ticks (Same as writing Response.Write ASP command)
------Asrar
Answerhere is the working version
<script type="text/javascript">
var currenttime = "<%= Now()%>" //SSI method of getting server date
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>
<p>
Current Server Time: <span id="servertime"></span></p>
Happy programming
-srini