Javascript toLocaleTimeString date object adds hour

I am trying to create a timer when the user clicks a button. To do this, I tried to calculate the difference between the two objects date. When I give out the difference, it works. However, the call toLocaleTimeStringreturns a string with the added 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>
Run codeHide result

What am I doing wrong?

+4
source share
2 answers

Specify the time zone in UTC in the argument options. Otherwise, the date differencewill be set to the time zone of the user agent.

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

Read more about the argument optionsand toLocaleTimeStringin 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>
Run codeHide result
+2
source

- JS - time.js timezone (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>
Hide result
+1

Source: https://habr.com/ru/post/1614169/


All Articles