我使用此代码在我的网站上显示简单的时钟:
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/)。我该如何解决这个问题?也许这个问题很奇怪,但我需要你的帮助!:)
答案 0 :(得分:0)
Date
功能基于用户的时钟。把你的时钟改为1980年,JavaScript会说它是1980年。
答案 1 :(得分:0)
只需拨打getUTCSeconds
而不是getSeconds
。
答案 2 :(得分:0)
getUTCMinutes()
和getUTCSeconds()
`
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版本的分钟和秒钟。