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

https://blog.csdn.net/qq_26230421/article/details/79064697

很多人会通过下列方式获取系统时间,并对时间进行处理:
//创建全局变量,也可以是局部的
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); 
    }
});
--------------------- 
作者:前方一片光明 
来源:CSDN 
原文:https://blog.csdn.net/qq_26230421/article/details/79064697 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值