js前端获取网络时间

获取网络时间

var xhr = new XMLHttpRequest();
if( !xhr ){
   xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("HEAD",location.href,true);
xhr.onreadystatechange=function(){
    if( xhr.readyState == 4 && xhr.status == 200 ){
         console.log(xhr.getResponseHeader("Date"));
         // console.log(dateTimeFormate(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;
  }
}

你可能感兴趣的:(js前端获取网络时间)