js 获取服务器时间

这个方法是网上找到的: 

//获取服务器时间
function getServerTime(){
    return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest(); //XMLHttpRequest 对象用于在后台与服务器交换数据。
        if( !xhr ){
            xhr = new ActiveXObject("Microsoft.XMLHTTP");  //老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象
        }  
        xhr.open("HEAD", location.protocol + "//" +location.host, true);  //获取服务器的HEAD的请求
		//accept-ranges: bytes cache-control: no-cache,no-cache content-encoding: gzip content-length: 191 content-type: text/plain date: Mon, 11 May 2020 05:44:33 GMT etag: "b4f95099808cce1:0" last-modified: Mon, 29 Jul 2013 17:25:19 GMT server: Microsoft-IIS/10.0 status: 304 vary: Accept-Encoding x-powered-by: ASP.NET
        xhr.onreadystatechange=function(){  
            if( xhr.readyState == 4 && xhr.status == 200 ){
                resolve(xhr.getResponseHeader("Date"))
            }  
        }  
        xhr.send(null);
    })
}
//时间格式化
function dateTimeFormate(date){
  if(!date){
    return
  }else{
    var d = new Date(date);
    var year = d.getFullYear();
    var month = ('0' + (d.getMonth() + 1)).slice(-2);
    var day = ('0' + (d.getDate())).slice(-2);
    var hour = ('0' + (d.getHours())).slice(-2);
    var minutes = ('0' + (d.getMinutes())).slice(-2);
    var seconds = ('0' + (d.getSeconds())).slice(-2);
    return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
  }
}

 

getServerTime().then( r=> {
	console.log(r);//得到的是美国时间

	let getServerTime = new Date(r);//转中国标准时间
	let serverTime = getServerTime.getTime();
	console.log(serverTime);//服务器时间戳

	let date = new Date(dateTimeFormate(r));//转日期格式 
	console.log(date);

	$.ajax({async:false}).getResponseHeader("Date");//同步请求响应头信息
	console.log($.ajax({async:false}).getResponseHeader("Date"));
});

 

你可能感兴趣的:(js,js,javascript)