Javascript's date object toLocaleTimeString adds an hour

jaunt

I'm trying to create a timer from when the user clicks a button. To do this I tried to calculate the difference between two date objects. When I output the difference, it works. However thetoLocaleTimeString call returns a string with an extra hour added:

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();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>

What am I doing wrong?

Drew Gaynor

Specify the time zone as UTC in the options argument. Otherwise, the difference date will be adjusted to the user agent's time zone.

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

Read more on the options argument and toLocaleTimeString in the MDN documentation.

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related