js 获取服务器当前时间

时间:2021-06-10 17:47:01

 //获取服务器时间

function getNowDate(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new window.XMLHttpRequest();
}else{
xhr = new ActiveObject("Microsoft")
}

xhr.open("GET","/",false)
xhr.send(null);
var date = xhr.getResponseHeader("Date");
date = new Date(date);
return date;
}

 

//获取当前时间

function getNowFormatDate() {

var date = new Date();
var char1 = "-";
var char2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentTime = date.getFullYear() + char1 + month + char1 + strDate
+ " " + date.getHours() + char2 + date.getMinutes()
+ char2 + date.getSeconds();
return currentTime;
}