Reputation: 37
(function() {
var start = new Date;
start.setHours(24, 0, 0);
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) {
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('last').innerHTML =
hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
I have a code which counts how much time left till certain time. But I need to reverse it and make it show how much time has passed since certain time.
Upvotes: 2
Views: 448
Reputation: 46
Since we are talking about the future therefore now > start
.
Also if now's hh
is less than start's hh
we should decrement the start's hh
.
So the code would be as follows:
(function() {
var start = new Date;
start.setHours(24, 0, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now < start) {
start.setDate(start.getDate() - 1);
}
var remain = ((now - start) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
var diff = hh + ":" + mm + ":" + ss;
console.clear();
console.log(diff);
setTimeout(tick, 1000);
}
tick()
})();
Upvotes: 3