Use JS to do time correction, get the time of the machine, there is a bug.
Use JS can also get to the server time, the principle is to use AJAX request, the return of the header information on the server side of the time information, get to it. Following:
1. Rely on jquery
Code:
function Getserverdate () {return
new date ($.ajax ({async:false}). getResponseHeader ("Date");
}
The above function returns a Date object, noting that you must synchronize when using AJAX, or you cannot return a time date.
No need to fill in the request link;
If the server time and local time are sometimes poor, you need to make corrections.
2. Native
Code:
function Getserverdate () {
var xhr = null;
if (window. XMLHttpRequest) {
xhr = new window. XMLHttpRequest ();
} else{//IE
XHR = new Activeobject ("Microsoft")
}
xhr.open ("Get", "/", false)//false immutable
xhr.send ( NULL);
var date = Xhr.getresponseheader ("date");
return new date (date);
Also returns a Date object, Xhr.open () must use synchronization;
No need to fill in the request link; open,send, and getResponseHeader must be written in sequence.
If you need to use asynchronous requests, you can listen to the onreadystatechange state to do different operations.
The code is as follows:
function Getserverdate () {
var xhr = null;
if (window. XMLHttpRequest) {
xhr = new window. XMLHttpRequest ();
} else{//IE
XHR = 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);}}
Using Asynchrony is not a convenient time to return.
Here the readystate has four states to facilitate different processing:
0: Request not initialized
1: The server connection has been established
2: Request received
3: In Request processing
4: The request is complete and the response is ready
Failed status, status value:
: "OK"
404: Page Not Found
The above is a small set to introduce JavaScript to get the server-side time method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!