Home > Web Front-end > JS Tutorial > body text

JavaScript method to get server-side time

高洛峰
Release: 2016-12-03 15:14:17
Original
1644 people have browsed it

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"));
}
Copy after login

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);
}
Copy after login

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);
}
}
}
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template