JavaScript Live Clock

Please provide an example of JavaScriptcode that would show the current time on the server.


Answer 1, authority 100%

Well, let’s say something like this:

<script type="text/javascript">
seconds = 0;
minutes = 0;
hours = 0;
function update_clock(){
$.post('gettime.php',function(data){
  data = eval('('+data+')');
  seconds = data.s;
  minutes = data.m;
  hours = data.h;
  updateDiv(hours,minutes,seconds);
});
}
function serverclock(){
  seconds++;
  if(seconds==60){
    seconds = 0;
    minutes++;
    if(minutes==60){
      minutes = 0;
      hours++;
      if(hours==24){
        hours = 0;
      }
    }
    if(minutes%10==0){
      update_clock();// ,     .
    }
  }
  updateDiv(hours,minutes,seconds);
}
function updateDiv(hours,minutes,seconds){
    $('#timediv').html(zeroPad(hours,2)+":"+zeroPad(minutes,2)+":"+zeroPad(seconds,2));
}
function zeroPad(num,count){ 
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad; 
}
return numZeropad;
}
update_clock();
setInterval('serverclock()',1000);
</script>
</head>
<body>
<div id="timediv"></div>
</body>

PHP:

<?php
print(date('{\h:H,\m:i,\s:s}'));
?>

Answer 2

Or if you have confused “server” with “client”:

alert(new Date().toString());

Answer 3

You might be interested in reading The clock shows server time, but on ajax with one request