I've written a simple JavaScript function based off some existing code that takes a specific UNIX time string (in the snippet: 1491685200
). It shows an alert if the specified time is still in the future. When that date has passed, it shows the elapsed days, hours and minutes whenever the function is called in-page.
I'm don't have much JavaScript object experience so it works just fine as-is, but I think it can be optimized further before I migrate my other stuff over to ES6.
function ElapsedTime () {
var nTotalDiff = Math.round((new Date()).getTime() / 1000) - 1491685200;
if (nTotalDiff >= 0) {
var oDiff = {};
oDiff.days = Math.floor(nTotalDiff / 86400);
nTotalDiff -= oDiff.days * 86400;
oDiff.hours = Math.floor(nTotalDiff / 3600);
nTotalDiff -= oDiff.hours * 3600;
oDiff.minutes = Math.floor(nTotalDiff / 60);
nTotalDiff -= oDiff.minutes * 60;
oDiff.seconds = Math.floor(nTotalDiff);
return oDiff;
} else {
alert('nTotalDiff still not >=0, so must be before the specified date');
}
}
function TimePassed() {
oDiff = ElapsedTime();
if(oDiff) {
alert(oDiff.days + 'd ' + oDiff.hours + 'h ' + oDiff.minutes + 'm ');
}
}
// document.getElementById('counter').addEventListener('click', TimePassed, false);