Javascript的日期对象toLocaleTimeString增加了一个小时

时间:2015-11-02 15:59:28

标签: javascript date

我尝试从用户点击按钮时创建计时器。 为此,我尝试计算两个['anyValue1', 'anyValue2', 'anyValue3', 'anyValue4', 'anyValue5', ......... 对象之间的差异。当我输出差异时,它可以工作。但是date调用返回一个添加了额外小时的字符串:



toLocaleTimeString

var start;
var timer;
function myTimer() {
  var current = new Date();
  var difference = new Date(current - start);
  console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
  document.getElementById("timer").innerHTML = difference;
  document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB');
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();




我做错了什么?

2 个答案:

答案 0 :(得分:2)

options参数中将时区指定为UTC。否则,difference日期将调整为用户代理的时区。

document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB', { timeZone: 'UTC' });

详细了解options参数以及MDN documentation中的toLocaleTimeString



var start;
var timer;
function myTimer() {
  var current = new Date();
  var difference = new Date(current - start);
  console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
  document.getElementById("timer").innerHTML = difference;
  document.getElementById("timer2").innerHTML = difference.toLocaleTimeString(navigator.language, { timeZone: 'UTC', hour12: false });
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();

<h1 id="timer"></h1>
<h1 id="timer2"></h1>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于JS和时区的问题,你最好使用像moment.js的时区(http://momentjs.com/timezone/)来做正确的转换(记住BST,GMT,国家之间的差异,等等..)。出于计时器的目的,以下内容也可以正常工作,并且更准确,更简单:

// Use Date.now() to get the time in milliseconds for this local computer
var start = Date.now();
var time  = new Date();
// This function will prepend a 0 to a number lower than 10
function prependZero(v){
  if(v < 9) return '0' + v;
  else return v;
}
var timer = setInterval(function() {
    // Calculate the difference using the computers local time strings
    var difference = new Date(Date.now() - start);
    document.getElementById("timer").innerHTML = new Date();
    // Now use the Date mnethods to get the correct output:
    document.getElementById("timer2").innerHTML = prependZero(difference.getHours()) + ':' + prependZero(difference.getMinutes()) + ':' + prependZero(difference.getSeconds());
}, 1000);
<h1 id="timer"></h1>
<h1 id="timer2"></h1>