Home > Article > Web Front-end > JavaScript method to get server-side time
There is a bug in using js for time correction and obtaining the local time.
You can also get the server time using js. The principle is to use ajax request. The returned header information contains the server-side time information. Just get it. The following:
1. Depend on jQuery
Code:
function getServerDate(){ return new Date($.ajax({async: false}).getResponseHeader("Date")); }
The above function returns a Date object. Note that it must be synchronized when using ajax, otherwise the time and date cannot be returned.
No need to fill in the request link;
If there is a time difference between the server time and the local time, correction needs to be made.
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不可变 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 order .
If you need to use asynchronous requests, you can listen to the onreadystatechange status to perform 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); } } }
It is not very convenient to use asynchronous return time.
The readyState here 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 has been Completed, and the response is ready
Failure status, status value:
200: "OK"
404: Page not found