Reputation: 3
In this post someone (royhowie) shared a js that counts to every sunday. This code works well but when I try to make it work for days beyond today (current day), like tuesday, monday by changing delta value from 7 to 2 or 1, this show Timer's Finished. How to make it work?
var getNextSunday = function () {
var today = new Date(),
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
delta = 7 - day;
var sunday = new Date(today.getTime() + (delta * 24 * 3600 * 1000));
sunday.setHours(11);
sunday.setMinutes(15);
sunday.setSeconds(0);
return sunday;
}
var t = getNextSunday(),
p = document.getElementById("time"),
timer;
var u = function () {
var delta = t - new Date(),
d = delta / (24 * 3600 * 1000) | 0,
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0,
m = (delta %= 3600 * 1000) / (60 * 1000) | 0,
s = (delta %= 60 * 1000) / 1000 | 0;
if (delta < 0) {
clearInterval(timer);
p.innerHTML = "timer's finished!";
} else {
p.innerHTML = d + "d " + h + "h " + m + "m " + s + "s";
}
}
timer = setInterval(u, 1000);
<h1 id="time"></h1>
@Reti43 Gentleman you are genius. Lots of respect for you.
Upvotes: 0
Views: 99
Reputation: 9796
Just simply change delta = 7 - day;
to
delta = (8 - day) % 7;
Explanation
Monday has the value 1, but this would be similar to 1+7.
After calculating the difference between 8 and today's date, use the modulo to get a remainder between 0 and 6.
Example
Today is Sunday: (8 - 0) % 7 = 8 % 7 = 1, i.e., Monday is 1 day away.
Today is Monday: (8 - 1) % 7 = 7 % 7 = 0, i.e., Monday is 0 days away.
Upvotes: 0
Reputation: 1187
that's a tricky question.
Instead of decrease the "7" you have to add to it:
var getNextWeekday = function (nextDesirefWeekDay) {
var today = new Date(),
day = today.getDay(),
delta = 7 - day + nextDesirefWeekDay;
...
}
Then, in nextDesirefWeekDay you pass your desired day:
0: Sunday 1: Monday 2: Tuesday ...
I hope that helps.
Upvotes: 0
Reputation: 1417
It's not the number 7 you want to change, its the value assigned to day:
Existing code:
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
You want:
day = 2, // 1 for Mon, 2 for Tue, 3 for Wed, etc.
Upvotes: 1