0

I use this code to show simple clock on my website:

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;
}

I noticed that seconds which getSeconds() function returns are not equal to GMT seconds (I use http://wwp.greenwichmeantime.com/). How can I fix that? Maybe this question is quite strange, but I need your help!:)

  • Note that time zones can be offset by 15 or 30 minutes, so if you wish to show UTC time you must get at least UTC hours and UTC minutes. Seconds and milliseconds should be the same. – RobG Mar 24 '16 at 05:33

4 Answers4

0

Date functions are based on the user's clock. Change your clock to 1980 and JavaScript will say it is 1980.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Just call getUTCSeconds instead of getSeconds.

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
0
  1. Your system clock might be wrong.
  2. You should use getUTCMinutes() and getUTCSeconds()
  3. Depending on what you mean by "wrong" (maybe just slightly off?), you can improve your timer like this:

`

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;
}

... which will try to always set up the timer so that it fires at actual second boundaries.

Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44
0

Don't assume time zone offsets are always at hour boundaries. There are time zones at the 15 minute granularity (e.g. Chatham Islands in NZ). If you're using .getUTCHours(), you should use the corresponding UTC versions of minute and second getters.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190