I am trying to implement a counter starts at 00:00:00 (hh:mm:ss) and shows it every second in a span. I am not getting to start with hour = 00. It shows me 10:00:00 at the beginning.
The code is following:
var startTimestamp;
function startTimer()
{
var startTimestamp = moment().startOf("day");
setInterval(function() {
startTimestamp++;
document.getElementById('timer').innerHTML =
moment.unix(startTimestamp).format('hh:mm:ss');
}, 1000);
}
Any idea why it doesn't work?
Since startTimestamp is a moment object you can modify its value using add() instead of using startTimestamp++. Note that add():
Mutates the original moment by adding time.
Then there is no reason to use moment.unix(), you can simply use format() on startTimestamp.
Finally, as format() docs states, lowercase hh stands for 01 02 ... 11 12 hours while uppercase HH stands for 00 01 ... 22 23, so I think you have to use the latter.
Here a live sample:
function startTimer()
{
var startTimestamp = moment().startOf("day");
setInterval(function() {
startTimestamp.add(1, 'second');
document.getElementById('timer').innerHTML =
startTimestamp.format('HH:mm:ss');
}, 1000);
}
startTimer();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<div id="timer"></div>
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