JS中的getSeconds()返回不等于GMT秒的秒数

时间:2016-03-23 12:48:55

标签: javascript date time gmt

我使用此代码在我的网站上显示简单的时钟:

function showClock() {
    var today = new Date(),
        h = today.getUTCHours(),
        m = today.getMinutes(),
        s = today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    $('.hour').html(h);
    $('.minutes').html(m);
    $('.seconds').html(s);

    setTimeout(showClock, 500);
}

function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

我注意到getSeconds()函数返回的秒数不等于GMT秒(我使用http://wwp.greenwichmeantime.com/)。我该如何解决这个问题?也许这个问题很奇怪,但我需要你的帮助!:)

4 个答案:

答案 0 :(得分:0)

Date功能基于用户的时钟。把你的时钟改为1980年,JavaScript会说它是1980年。

答案 1 :(得分:0)

只需拨打getUTCSeconds而不是getSeconds

答案 2 :(得分:0)

  1. 您的系统时钟可能有误。
  2. 您应该使用getUTCMinutes()getUTCSeconds()
  3. 根据你所说的“错误”(可能只是略微关闭?),你可以像这样改进你的计时器:
  4. `

    function showClock() {
      var today = new Date(),
        h = today.getUTCHours(),
        m = today.getUTCMinutes(),
        s = today.getUTCSeconds(),
        ms = today.getUTCMilliseconds();
      h = checkTime(h);
      m = checkTime(m);
      s = checkTime(s);
    
      console.log(h + ':' + m + ':' + s);
    
      setTimeout(showClock, 1000 - ms);
    }
    
    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    

    ...将尝试始终设置计时器,使其在实际的第二边界处触发。

答案 3 :(得分:0)

不要假设时区偏移总是在小时边界。在15分钟的粒度上存在时区(例如Chatham Islands in NZ)。如果您正在使用.getUTCHours(),则应使用相应的UTC版本的分钟和秒钟。