Reputation: 27
I'm trying to make a count down timer that counts down to a couple different hours depending on the time of the day.
Here's how I've tried to set the function for the time. So if its before 14.00, it would count down to 14.00 and if it's after 14.00, it would count down to 20.00. After 20.00, it would show the count down to 14.00 tomorrow.
Ive tried to set the target time like this, but setting the date for "tomorrow at 14.00" I just cant get to work.
var target_date = new Date();
var currentdate = new Date();
if (currentdate.getHours() > 0 && currentdate.getHours() < 14) {
target_date.setHours(14,0,0,0);
}
else if (currentdate.getHours() > 14 && currentdate.getHours() < 20) {
target_date.setHours(20,0,0,0);
}
else {
target_date.setDate(currentdate.getDate()+1).setHours(16,0,0,0); // if 20-24, count down to tomorrow at 14.00
}
The rest of the script for the count down is
var days, hours, minutes, seconds;
var countdown = document.getElementById("countdown");
setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = hours + "t "
+ minutes + "m";
}, 1000)};
Upvotes: 1
Views: 1849
Reputation: 3383
target_date.setDate(currentdate.getDate()+1).setHours(16,0,0,0);
setDate()
method doesn't return Date
object, so this sequence wouldn't work
You should write
target_date.setDate(currentdate.getDate()+1);
target_date.setHours(16,0,0,0);
Upvotes: 1