Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's date object toLocaleTimeString adds an hour

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?

like image 460
jaunt Avatar asked Nov 02 '15 15:11

jaunt


People also ask

How to add hours to date object JavaScript?

To add hours to a Date in JavaScript:Use the getTime() method to get the number of milliseconds since the Unix Epoch. Use the setTime() method, passing it the result of calling getTime plus the hours converted to milliseconds.

How do I use toLocaleTimeString () without displaying seconds?

To use the toLocaleTimeString() method without displaying seconds, set the hour and minute parameters in the method's options object, e.g. date. toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}) .

What is toLocaleTimeString in JavaScript?

The toLocaleTimeString() method returns a string with a language-sensitive representation of the time portion of the date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat .


1 Answers

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>
like image 68
Drew Gaynor Avatar answered Sep 28 '22 16:09

Drew Gaynor