Svante
Svante

Reputation: 45

JavaScript countdown until date

So I'm trying to build a very minimalistic countdown timer until a specific date (2015 July 31, 18:00:00 GMT) including total MS until the date, as well as a D:H:M:S:MS until the date.

What I got so far is at this codepen: http://codepen.io/svbeon/pen/MwBJNJ With this JS:

setInterval(times, 1);
function times() {
today = new Date();
July = new Date(Date.UTC(2015,06,31,18,0,0,0));
diffMs = ((July - today) - today.getTimezoneOffset() * 60000); // milliseconds between now & July 31 
diffDays = (July.getDate() - today.getDate()); // days
diffHrs = (24 + ((July.getHours() - today.getHours()) + (today.getTimezoneOffset() / 60))); // hours
diffMins = (60 + (July.getMinutes() - today.getMinutes())); // minutes
diffSecs = (60 + (July.getSeconds() - today.getSeconds())); // seconds
diffMis = (1000 + (July.getMilliseconds() - today.getMilliseconds())); //milliseconds


if (diffMs <= 0) {
    diffMs = 0;
    diffDays = 0;
    diffHrs = 0;
    diffMins = 0;
    diffSecs = 0;
    diffMis = 0;
    }

document.getElementById("timer").innerHTML = diffMs + " miliseconds";
document.getElementById("timer2").innerHTML = diffDays + " days " + diffHrs + " Hours " + diffMins + " Minutes " + diffSecs + " seconds " + diffMis + " milliseconds";
document.getElementById("date").innerHTML = "until " + July;
}

The problems I get here is that it can echo something like 14 days 24 hours 60 minutes 60 seconds 1000 milliseconds when it in fact should be 14 days 0 hours 0 minutes 0 seconds 0 milliseconds as well as after 18:00 UTC it still says 14 days instead of 13 days until midnight.

I got no real idea of how to simply fix these problems Adding one less for example:

diffSecs = (59 + (July.getSeconds() - today.getSeconds())); // seconds

Will result in the timer showing 0 instead of 60, but will as well make the timer go 1 second wrong (minute or hour if you have it on their part)

So if you happen to have any idea how to fix this and help a not so skilled developer iIwould be really happy!!

Upvotes: 1

Views: 1620

Answers (2)

krl
krl

Reputation: 5296

I'd suggest using Moment.js, as it makes date/time manipulation much simpler and will probably help you solve this problem also.

For instance to get a difference between two dates in milliseconds:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

Then create a duration from the result of the difference in milliseconds and use milliseconds(), seconds(), etc functions to display duration in different units:

moment.duration(1500).milliseconds(); // 500
moment.duration(1500).seconds(); // 1

Partial solution: https://jsfiddle.net/krlkv/xvstvfdb/3/

Upvotes: 1

Nursultan Zarlyk
Nursultan Zarlyk

Reputation: 412

Just use mod:

day = day%24; secs = secs%60;

and etc.

Upvotes: 0

Related Questions