首页 Javascript 正文
284

Javascript动态显示当前时间

  • yiqingpeng
  • 2016-12-17
  • 0
  •  
此方法最大的特点是以服务器时间为基础显示当前时间,增加了时间的准确性。注意要引入jquery, 因为用到了jquery的ajax方法。
代码:
(function(cb){
        function timer(start, cb){
            this.cur_seconds = start;
            this.callback = cb;
            this.timerId = 0;
            this.stop = function(){
              this.timerId>0 && clearInvterval(this.timerId);
            }
            this.start = function(){
              this.timerId = setInterval((function(obj){
                return function(){
                  obj.cur_seconds += 1000;
                  typeof obj.callback == 'function' && obj.callback(obj.cur_seconds);
                }
              })(this), 1000);
            } 
        }
        $.ajax({
          type: 'HEAD',
          url : window.location.href,
          async: true,
          cache: false,
          complete : function(xhr){
                  var dateStr = xhr.getResponseHeader('Date'), date = new Date(dateStr);
                  new timer(date.getTime(), function(t){
                    cb(t);
                  }).start();                
          }
        });
      })(function(t){
          var formatDate = (function(fmt, date){
              return fmt.replace(/y/g, date.getFullYear()).replace(/m/g,(date.getMonth()+1).toString().replace(/\b(\d)\b/,'0$1')).replace(/d/g, date.getDate().toString().replace(/\b(\d)\b/,'0$1')).replace(/H/g, date.getHours().toString().replace(/\b(\d)\b/,'0$1')).replace(/M/g, date.getMinutes().toString().replace(/\b(\d)\b/,'0$1')).replace(/S/g, date.getSeconds().toString().replace(/\b(\d)\b/,'0$1'));
          })('y年m月d日 H:M:S', new Date(t));
          $('#cur_time_clock').val(formatDate);
      });

正在加载评论...