When JavaScript is used to get the server-side time, it is a bug to use js to correct the time and obtain the local time.
Js can also be used to obtain the server time. The principle is to use ajax requests. The returned header information contains the time information of the server. Below:
1. dependent on jQuery
Code:
function getServerDate(){return new Date($.ajax({async: false}).getResponseHeader("Date"));}
The preceding function returns a Date object. Note that the data must be synchronized when ajax is used. Otherwise, the time and Date cannot be returned.
No request link is required;
If there is a time difference between the server time and the local time, correction is required.
2. Native
Code:
Function getServerDate () {var xhr = null; if (window. XMLHttpRequest) {xhr = new window. XMLHttpRequest ();} else {// iexhr = new ActiveObject ("Microsoft")} xhr. open ("GET", "/", false) // false variable xhr. send (null); var date = xhr. getResponseHeader ("Date"); return new Date (date );}
A Date object is returned, and xhr. open () must be synchronized;
You do not need to enter the request link; open, send, and getResponseHeader must be written in order.
To use asynchronous requests, you can listen to the onreadystatechange status for different operations.
The Code is as follows:
function getServerDate(){var xhr = null;if(window.XMLHttpRequest){xhr = new window.XMLHttpRequest();}else{ // iexhr = new ActiveObject("Microsoft")}xhr.open("GET","/",true);xhr.send(null);xhr.onreadystatechange=function(){var time,date;if(xhr.readyState == 2){time = xhr.getResponseHeader("Date");date = new Date(time);console.log(date);}}}
Asynchronous Method is not very convenient to return time.
Here, the readyState has four States to facilitate different processing:
0: the request is not initialized.
1: The server connection has been established.
2: The request has been received
3: The request is being processed
4: The request is complete and the response is ready.
Failed status. Value of status:
200: "OK"
404: Page not found