嘿, 我是Mofei!
Getting Server System Time with Javascript

Background

Many times, applications like lotteries, countdowns, etc. need to use time, but simply using new Date() to get local time is very unreliable, as anyone can easily modify it. This is when we need to use system time. Typically, we would agree on an interface with the server that's used to return the system time. However, in real projects, this interface can be omitted; we can obtain the server time through another method.

Related Technologies

If you're familiar with HTTP programming, you'll immediately think of something, right? Yes! It's the HTTP headers.

In most cases, the HTTP headers contain a lot of useful information. Below is the HTTP headers of Baidu's homepage:

HTTP/1.1 200 OK
Date: Tue, 24 Jun 2014 09:29:29 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: Keep-Alive
Set-Cookie: BDRCVFR[Y7OWRVY3J9s]=I67x6TjHwwYf0; path=/; domain=.baidu.com
Set-Cookie: BDSVRTM=92; path=/
Set-Cookie: H_PS_PSSID=1468_7236_7157_7254; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Cache-Control: private
Expires: Tue, 24 Jun 2014 09:29:29 GMT
Content-Encoding: gzip
Server: BWS/1.1
BDPAGETYPE: 2
BDQID: 0xd4c3d37f00019464
BDUSERID: 29250924

Here, we focus on the Date field. If we can access this field, everything will be simple!

So how do we access it?

It's very simple; we use the xmlhttp object's getResponseHeader('Date') method.

Implementation

Now that we know the method, it's straightforward.

First, we send a request (AJAX) to the server, and then extract the Date field from the response headers, and we are done!

I have encapsulated this process into a small plugin: sysDate

Those interested can check out the source code

It's also easy to use.

var a=sysDate(option);

// Optional field option, {'url':'/getDate'}
a.done(function(data){
    console.log('done',data);
    // Server time data 1385003673000'
});

It also supports asynchronous calls (it feels a bit like promises).

var a=sysDate();

// Here you can write the callback inside the async function
// After waiting for 3 seconds, we register the done event, which works just as well. Isn't it amazing?
setTimeout(function(){
  a.done(function(data){
    console.log('done',data);
    //it will return 'done 1385003673000'
  });
},3000)

Download and Source Code

Students interested can click here to get the source code, and remember to star it :)

THE END

More Articles You Might Be Interested In

Have questions or a different perspective? Let’s discuss in the comments!

avatar

Mofei's Friend (Click to edit)

The world is big, say something!

HI. I AM MOFEI!

NICE TO MEET YOU!