取服务器时间的最佳实践

  2011-01-13


很多场景中,我们都需要拿到服务器的时间,一般的实现方式是写个CGI,把服务器时间吐出来。但CGI容易带来安全或性能的问题。
这里的例子,使用HEAD请求,解析HTTP HEADER中的时间,从而达到同样目的。

var xhr=null;
try{xhr=new XMLHttpRequest();}catch(e){try{xhr=new ActiveXObject(“Msxml2.XMLHTTP”);}catch(e){try {xhr=new ActiveXObject(“Microsoft.XMLHTTP”);}catch (e){xhr=null;} } };
xhr.open(“HEAD”, window.location.href, false);
xhr.send(null);
var t = parseInt(new Date(Date.parse(xhr.getResponseHeader(“Date”))).getTime() / 1000);