开发者

Best method for getting an accurate timestamp?

I am working on an app where there is a need for a reliable, accurate timestamp in JavaScript. As such, I would prefer not to rely on the client system time. Although it is likely to be correct, I need something more certain.

I was hoping there was an API available from a well endowed provider such as Google that would allow me to access an accurate timestamp from some server somewhere. I haven't been able to find that, so I came up with another idea: create a tiny dummy file on our server, retrieve it via AJAX and extract our own server's timestamp from response headers:

$.ajax({
 type: 'POST',
 url: 'dummy.json',
 complete: function (response) {
   // header is available as a string: response.getAllResponseHeaders();
 }
}

Headers:

Date: Fri, 14 Oct 2011 14:07:41 GMT
Content-length: 18
Last-modified: Thu, 13 Oct 2011 20:35:28 GMT
Server: Netscape-Enterprise/6.1 AOL
Etag: "0-0-12-0"
Content-type: text/plain
Accept-ranges: bytes

Is this not开发者_运维百科 the most ridiculous work-around ever? Am I going crazy? Is there a better solution?

If not could somebody help me write a regex to extract just the date from the above response header string?

edit: forgot to mention the reason why this is a problem is I don't have access to the backend to create some simple service for polling a timestamp from the server or anything like that. I have to do it in JavaScript for this particular application.


Nothing wrong with your solution, but there are plenty of web services out there. Google quickly reveals this service from Yahoo and this one from earthtools. They all work, it's just a matter of choosing the one that fits best for you.


This one is in JSON format with seperate properties available (seconds etc). You can choose the time zone and also supports JSONP.


Why not have the server send a cookie with the current time - that at least would be available in the initial request's document.cookie property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜