JavaScript function to get server time

Source: Internet
Author: User
Tags local time


All along, we want to use JS to get accurate time, that is, Beijing time, when after all, JS is the client language, can only get to the local time, and this in our project is often inaccurate, we can not guarantee that the user's computer time is accurate, So we typically use the server-side language to get the server's time.

Although the server-side language acquisition time is easy, but for the front-end developers have no effect, they need to use JS to obtain accurate time, the following is a way to use JS to obtain server time:

When the background program passes the page elements to the browser there will be a response Header, which has a field date that marks the time the server responds, and we just have to find a way to get the time right.

var xhr = new XMLHttpRequest ();
if (!XHR) {
XHR = new ActiveXObject ("Microsoft.XMLHTTP");
}
Xhr.open ("Head", location.href,true);
Xhr.onreadystatechange=function () {
if (xhr.readystate = = 4 && xhr.status = 200) {
var str = xhr.getresponseheader ("Date"); Get date In response header
var date = new Date (str). GetTime (); Convert date to Time object
alert (date); Output time stamp
}
}
Xhr.send (NULL);

If you use JQ, you can do this.


$.ajax ({
URL: ',
Type: ' Get ',
Success:function (data, status, XHR) {
var str = xhr.getresponseheader (' Date '); Get date In response header
var date = new Date (str). GetTime (); Convert date to Time object
alert (date); Output time stamp
}
});

This method obtains the server time to be quite reliable.

This is actually AJAX to get the time, there is a way to load the page from PHP to generate server time, and then the conversion from JS.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.