很多人会通过下列方式获取系统时间,并对时间进行处理:
var time,year,month,date,hours,minutes,seconds;
time = new Date();
year = time.getFullYear();
//对日期进行处理,小于10的数在前面加上0
month = (time.getMonth()+1)<10?("0"+(time.getMonth()+1)):(time.getMonth()+1);
date = time.getDate()<10?("0"+time.getDate()):time.getDate();
hours = time.getHours()<10?("0"+time.getHours()):time.getHours();
minutes = (time.getMinutes()<10?("0"+time.getMinutes()):time.getMinutes());
seconds = (time.getSeconds()<10?("0"+time.getSeconds()):time.getSeconds());
//拼格式,如:2018-01-15 14:32:57
time = year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
//赋值
$("#registerTime").val(time);
但是这获取的是本地的电脑系统时间如下图,系统时间是可以修改的,相对来说不太准确: 所以,这时候需要使用服务器时间来解决时间不准确的问题
下面是通过ajax访问服务器,通过error回调函数进行处理:
var time,year,month,date,hours,minutes,seconds;
//通过ajax访问服务器,获取服务器时间
$.ajax({
type:"OPTIONS",
url:"/",
error:function(a){
time = new Date(a.getResponseHeader("Date"));
year = time.getFullYear();
//小于10的数在前面加上0
month = (time.getMonth()+1)<10?("0"+(time.getMonth()+1)):(time.getMonth()+1)
date = time.getDate()<10?("0"+time.getDate()):time.getDate();
hours = time.getHours()<10?("0"+time.getHours()):time.getHours();
minutes = (time.getMinutes()<10?("0"+time.getMinutes()):time.getMinutes());
seconds = (time.getSeconds()<10?("0"+time.getSeconds()):time.getSeconds());
//拼格式,2018-01-15 19:05:33
time = year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
//赋值
$("#registerTime").val(time);
}
});
OK,GAME OVER!