JS how to get server-side time?

Source: Internet
Author: User
Tags local time

Use JS to do time correction, get the local time, there is a bug.

The use of JS can also get to the server time, the principle is to use the AJAX request, the header information returned contains the server-side time information, get to it. Following:

1. Rely on jquery

Code:

function getserverdate () {    returnnewfalse}). getResponseHeader ("Date"));

The above function returns a Date object that must be synchronized when using Ajax, or the time date cannot be returned.

No need to fill out the request link;

If the server time and local time are sometimes poor, you need to make corrections.

2. Native

Code:

functiongetserverdate () {varXHR =NULL; if(window. XMLHttpRequest) {XHR=Newwindow.    XMLHttpRequest (); }Else{//IEXHR =NewActiveobject ("Microsoft")} xhr.open ("GET", "/",false)//false immutable Xhr.send (NULL); varDate = Xhr.getresponseheader ("date"); return Newdate (date);}

Also returned is a Date object, Xhr.open () must use synchronization;

No need to fill out the request link; open,send, and getResponseHeader must be written sequentially.

To use asynchronous requests, you can listen to the onreadystatechange state to do different things.

The code is as follows:

functiongetserverdate () {varXHR =NULL; if(window. XMLHttpRequest) {XHR=Newwindow.    XMLHttpRequest (); }Else{//IEXHR =NewActiveobject ("Microsoft")} xhr.open ("GET", "/",true); Xhr.send (NULL); Xhr.onreadystatechange=function(){        vartime,date; if(Xhr.readystate = = 2) { time= Xhr.getresponseheader ("Date"); Date=NewDate (time);        Console.log (date); }    }}

Using Async is not a convenient time to return.

There are four kinds of readystate, which are convenient for different treatments:

    • 0: Request not initialized
    • 1: Server Connection established
    • 2: Request received
    • 3: In Request processing
    • 4: The request is complete and the response is ready

Failed state, status value:

$: "OK"

404: Page Not Found

JS how to get server-side time?

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.