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?
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.
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'}) .
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 .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With