JQuery获取服务器时间

从客户端获取时间方法:

function setTime(){
      var dt=new Date();
      var arr_week=new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
      var strWeek=arr_week[dt.getDay()];
      var strHour=dt.getHours();
      var strMinutes=dt.getMinutes();
      var strSeconds=dt.getSeconds();
      if (strMinutes<10) strMinutes="0"+strMinutes;
      if (strSeconds<10) strSeconds="0"+strSeconds;
      var strYear=dt.getFullYear()+"年";
      var strMonth=(dt.getMonth()+1)+"月";
      var strDay=dt.getDate()+"日";
      <!--var strTime=strHour+":"+strMinutes+":"+strSeconds;-->
      strTime=strHour+":"+strMinutes;
      time.innerHTML=strYear+strMonth+strDay+" "+strTime+"  "+strWeek;
  }

从服务端获取时间方法:

function setTime() {
    //创建全局变量,也可以是局部的
    var time, year, month, date, hours, minutes, seconds;
    //通过ajax访问服务器,获取服务器时间
    $.ajax({
        async: false,
        type: "GET",
        success: function(result, status, xhr) {
            time = new Date( xhr.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;
           alert(time);
        },
        error: function (a) {

        }
    });
}

猜你喜欢

转载自blog.csdn.net/huangli1466384630/article/details/86299931
今日推荐