I’m currently learning some Javascript, and I’d made a realtime clock (well actually I modded W3school’s code but whatever…I already figured out how to make a clock in PHP so no sense repeating that…)
Butttt the realtime clock doesn’t seem to sync up with different devices, and I’d like to know why.
W3schools explains the date object as a count of the milliseconds since 1970, so I can’t see why it would be wrong….it looks to me like instead of doing that, it’s just mirroring whatever the computer’s clock is.
When I pull up the website on a smartphone, the clock is 30 seconds or so off.
Is there maybe some way to make the clock reflect server time instead of each user’s computer?
Here is the code
var ampm = "AM"; //Default
var message="";
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
window.onload=startTime;
Your code is executed on “client” device – your smartphone, PC whatsoever.
So you have a time set on this device. This ‘Date’ object actually doesn’t know anything about the time on server. The time is determined by the underlying Operating system installed on the client machine.
Your question is not really related to some specific technology (like Java Script, for instance), but rather how to get time synchronized on server and client machine.
Its quite complicated actually.
You can take a step further and ask how you can synchronize time between devices that belong to different time-zones. How about different calculations that should take into consideration ‘daylight saving’ time period?
As the common answer for time synchronization between computers you can read about Network Time Protocol, NTP