您可以在代码中使用NTP(网络时间协议)来计算准确的时间,
我尝试为您解释:
我们在发送请求时使用ClientTime(例如4/3/2012 13:56:10.123)
您将ClientTime发送到服务器
我们有用于请求的往返时间,我将其称为RequestTime(例如:花费5秒)
在“服务器”中,我们计算服务器与客户端之间的时差时间(例如:It ServerTime-ClientTime = ServerClientDifferenceTimeWithRequestTime),您现在应该在步骤3中将此差值包括往返请求时间,然后从差异中删除往返时间
服务器发送响应,其中包括ServerClientDifferenceTimeWithRequestTime和ServerTime
我们有用于响应的往返时间,我将其称为ResponseTime(例如:花费3秒)
在客户端中,我们再次计算服务器与客户端之间的时差时间(例如:It ServerTime-ClientTime = ServerClientDifferenceTimeWithResponseTime),现在:您现在应该在步骤6中包含此差异,包括往返响应时间
我们现在有时间在客户
您应该在客户端中计算简单方程式:
X(SyncedTime) =Now + (ServerClientDifferenceTimeWithRequestTime - RquestTime)
X(SyncedTime) =Now + (ServerClientDifferenceTimeWithResponseTime - ResponseTime)
Now - ClientTime = RquestTime + ResponseTime =>
Now - (ServerClientDiffRq - RquestTime) = Now - (ServerClientDiffRs - ResponseTime)
如果您解决它,您会发现:
ResponseTime = (ServerClientDifferenceTimeWithRequestTime - Now + ClientTime + - ServerClientDifferenceTimeWithResponseTime )/2
然后您可以使用以下等式在客户端中找到同步时间或服务器时间:
X(SyncedTime) =Now + (ServerClientDifferenceTimeWithResponseTime - ResponseTime)
我显示了简单的代码,但是当您要编写它时,请不要忘记使用UTC日期和时间函数...
服务器端(例如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+"}");
客户端(带有Jquery的 Javascript ):
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);
});