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

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

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!

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前方一片光明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值