Pages

Tuesday, September 20, 2011

Server side (web) clock on your client's browser

There you can find many number or Javascript clocks available on the Internet, graphical as well as numerical. But all they do is showing the clock in the client's machine. What if the client machine's time is not correct? or the viewer is from another region or timezone but you need to display the clock according to your regional or server time. Here is the solution.

I'm calling this in my page onload event;
<BODY onLoad="startTimee(<? echo $a ?>, <? echo $b ?>, <? echo $c ?>)">

Here is my piece of PHP code, this should be located before the <body> tag;
<?
$a = date('H');
$b = date('i');
$c = date('s');
?>

Finally my simple Javascript, displays the server ticking clock;
<script type="text/javascript">
var a;
var b;
var c;
<! --This should be defined before all JS functions so it will work as global values for JS. -->


function startTimee(x, y, z)
{


var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
 a=x-h;
 b=y-m;
 c=z-s;
startTime();
}


function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();


h=h+(a);
m=m+(b);
s=s+(c);


if (s>59)
{
s=(s)-60;
m=m+1;
}


if (s<0)
{
s=60+(s);
m=m-1;
}


if (m>59)
{
m=(m)-60;
h=h+1;
}


if (m<0)
{
m=60+(m);
h=h-1;
}


if (h>12)
{
h=h-12;
}


// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}


function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>

What I all do is taking the time difference with my server and clients machine on page load and assignees them to JS global values. Finally add (or subtract) it to the normal JS clock. Simple as that, (but powerful :) ) So you can embed this with any JS clock on the web as your requirement.

Note: the actual time may be differ + or - 5 to 10 seconds depending on the page load time.

Regards,

No comments:

Post a Comment