The best way to synchronize client-side javascript clock with server date

n0s picture n0s · Oct 28, 2009 · Viewed 75.8k times · Source

I have a task to show digital clock (with minutes precision) on HTML page in some fixed timezone (MSK or MSD - depending on current date). I'd like to avoid relying on client system clock, so some synchronization with server is required. HTTP server sends Date header in each response so we can send an AJAX GET or HEAD request to any URL of our site to get server date, calculate the difference with client date and use it when updating clock with setTimeout(). There are other issues remains: timezone switching for daylight settings, latency accounting for very slow connections.

Any idea to this task the simpliest way? I'd prefer to solve it without server-side programming.

Answer

Mehdi Yeganeh picture Mehdi Yeganeh · Apr 3, 2013

You can calculate exact time with NTP (Network Time Protocol) in your codes,

i try to explain for you:

  1. We have ClientTime on Sending Request (for example 4/3/2012 13:56:10.123)
  2. You send ClientTime to Server
  3. We have Round-trip time for request, i called it RequestTime (for example: It takes 5 seconds)
  4. In Server, We calculate Difference time between Server and Client (for example: It ServerTime - ClientTime = ServerClientDifferenceTimeWithRequestTime), you should now this Difference including Round-trip request time in step 3 then you should remove round trip time from Difference
  5. Server Send response that include ServerClientDifferenceTimeWithRequestTime and ServerTime
  6. We have Round-trip time for response, i called it ResponseTime (for example: It takes 3 seconds)
  7. In client, We calculate Difference time between Server and Client again (for example: It ServerTime - ClientTime = ServerClientDifferenceTimeWithResponseTime), again: you should now this Difference including Round-trip response time in step 6
  8. We have Now time in Client
  9. You should Calculate simple equations in client:

X(SyncedTime) = Now + (ServerClientDifferenceTimeWithRequestTime - RquestTime)

X(SyncedTime) = Now + (ServerClientDifferenceTimeWithResponseTime - ResponseTime)

Now - ClientTime = RquestTime + ResponseTime =>

Now - (ServerClientDiffRq - RquestTime) = Now - (ServerClientDiffRs - ResponseTime)

if you solve it you found this:

ResponseTime = (ServerClientDifferenceTimeWithRequestTime - Now + ClientTime + - ServerClientDifferenceTimeWithResponseTime )/2

and then you can found synced time or server time in client with this equation:

X(SyncedTime) = Now + (ServerClientDifferenceTimeWithResponseTime - ResponseTime)

I show simple code but when you want write it don`t forgot use UTC date & time functions...

Server Side (for example php, c#):

PHP:

header('Content-Type: application/json; charset=utf-8');
$clientTime = $_GET["ct"] * 1; //for php 5.2.1 or up: (float)$_GET["ct"];
$serverTimestamp = round(microtime(true)*1000); // (new DateTime())->getTimestamp();
$serverClientRequestDiffTime = $serverTimestamp - $clientTime;
echo "{\"diff\":$serverClientRequestDiffTime,\"serverTimestamp\":$serverTimestamp}";

C#:

long clientTime = long.Parse(Request.Form["ct"]);
long serverTimestamp = (DateTime.Now.Ticks-(new DateTime(1970,1,1) - DateTime.MinValue).Ticks) / 10000;
long serverClientRequestDiffTime = serverTimestamp - clientTime;
Response.Write("{\"diff\":"+serverClientRequestDiffTime+",\"serverTimestamp\":"+serverTimestamp+"}");

Client Side (Javascript with Jquery):

var clientTimestamp = (new Date()).valueOf();
$.getJSON('http://yourhost.com/getdatetimejson/?ct='+clientTimestamp, function( data ) {
    var nowTimeStamp = (new Date()).valueOf();
    var serverClientRequestDiffTime = data.diff;
    var serverTimestamp = data.serverTimestamp;
    var serverClientResponseDiffTime = nowTimeStamp - serverTimestamp;
    var responseTime = (serverClientRequestDiffTime - nowTimeStamp + clientTimestamp - serverClientResponseDiffTime )/2

    var syncedServerTime = new Date((new Date()).valueOf() + (serverClientResponseDiffTime - responseTime));
    alert(syncedServerTime);
});