您的位置:首页 > Web前端 > JavaScript

JavaScript获取系统时间以及通过ajax获取服务器时间

2018-01-15 15:03 295 查看

很多人会通过下列方式获取系统时间,并对时间进行处理:

//创建全局变量,也可以是局部的
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);
}
});


觉得有用就点个赞喽!~(@^_^@)~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: