Goal: Once the time hits two days or less, then it switches to hours instead of days.
Problem: In checking code by changing the date, it still only shows the days left, and not the hours. Am I missing something?
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
if (distance < 2) {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = hours + " hours left";
}
else if (distance < 0) {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = "The time has ended.";
}
else {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = days + " days left";
}
});
The Date method getTime returns:
the number of milliseconds* since the Unix Epoch.
Your code countDownDate - now returns the number of milliseconds from now until the target date.
However, your comparison distance < 2 is treating distance (which is in ms) as if it were in days.
You probably want
ms in seconds ------------------+
seconds in hour ---------+ |
hours in day ------+ | |
days -+ | | |
| | | |
if (distance < 2 * 24 * 3600 * 1000) {
/* ... */
}
With help of the previous two responses, I figured it out. I added "2x" to the hours variable and changed the variable to days in the if statements and rid of the setInterval because it wasn't needed (I only need days and hours, not milliseconds and for it to constantly be firing):
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();
$(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor(
(2 * (distance % (1000 * 60 * 60 * 24))) / (1000 * 60 * 60)
);
document.getElementById("aep-countdown-date").innerHTML =
days + " days left.";
if (days < 0) {
document.getElementById("aep-countdown-date").innerHTML = "Time has ended.";
}
if (days < 2) {
document.getElementById("aep-countdown-date").innerHTML =
hours + " hours left.";
}
});
Related
I created 1 min time loop for my website. If the timer ends it will show some results.after that timer will start again 1:00. But sometimes error comming like, something time going very high (2 min ,50min, 5sec, 1sec ). It not stay in 1min loop. Please help me sir to fix this error.
Code:
function timerFunc(date) {
// Set the date we're counting down to
var countDownDate = new Date(date).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var forseconds = prependZero(seconds);
// Output the result in an element with id="demo"
document.getElementById("timer").innerHTML = "0" + minutes + ": " + forseconds;
// If the count down is over, write some text
if (distance <= 0) {
clearInterval(x);
}
}, 1000);
}
function prependZero(number) {
if (number <= 9)
return "0" + number;
else
return number;
}
<span id="timer"></span>
We had this countdown for Christmas, but now it shows expired instead of resetting to next year
// Set the date we're counting down to
var year = new Date().getFullYear();
var countDownDate = new Date("Dec 24, " + year + " 23:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="clock"
document.getElementById("clock").innerHTML = days + " days " + hours + "hrs. " + minutes + "mins. " + seconds + "secs. ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
}, 1000);
The 'expired' message should maybe show during the 25-26th of December and then reset back to counting on 27th till next year?
I cant see where you check if your date is later than december, 26th, here should be code like this
if (days < -2) {
countDownDate = new Date("Dec 24, " + (year + 1) + " 23:00:00").getTime();
} else if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
or better just in the very beginning write
var now = new Date()
var year = now.getFullYear() + (now.getMonth() == 11 && now.getDate() > 26)
Below are suggested edits to your code. Near the top, we decide which year's Christmas to count down to.
If you look over the code and commments, you can see more about how date information can be used in JavaScript.
If you want to know more, there's great information at MDN's Date Object page.
// Get a Date object for the current time before starting the countdown
let startTime = new Date()
// Get the year, month and day from the date object
let year = startTime.getFullYear();
let monthIndex = startTime.getMonth();
let dayOfMonth = startTime.getDate();
//console.log (`${year} ${monthIndex} ${dayOfMonth}`);
if (monthIndex === 11 && dayOfMonth > 27){ // Jan has monthIndex == 0
year = year + 1; // Use next year
}
// Set the date we're counting down to
let countDownDate = new Date("Dec 24, " + year + " 23:00:00").getTime();
// Start the countdown, updating the display every 1 second
var x = setInterval(function() {
// Get a Date object for the current second of the countdown
var date = new Date()
// Get the timestamp from the Date object
var now = date.getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Function to show "day" if 1 day, "days" if 2 or more days, etc.
function pluralIfAppropriate(value, singularLabel, pluralLabel){
if(value == 1){
return singularLabel;
}
else{
if(pluralLabel == undefined){
pluralLabel = singularLabel + "s";
}
return pluralLabel;
}
}
// Builds the display text
let displayText = `${days} ${pluralIfAppropriate(days, "day")} ${hours}${pluralIfAppropriate(hours, "hr")} ${minutes}${pluralIfAppropriate(minutes, "min")} ${seconds}${pluralIfAppropriate(seconds, "sec")}`;
// Displays the displayText in the element with id="clock"
document.getElementById("clock").innerHTML = displayText;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
}, 1000);
<p id="clock"></p>
I want reverse timer for session time out. I got one code on codepen. This code is clockwise timer , I tried to make it anti-clock wise , I am failed. Please suggest me. I want to make 1 hour or 59min 59sec time out. Please help me Here is the codepen demo.
if((intervalCounter%1000)==0){
currentTime += 1000;
var appendHour = currentTime / (1000 * 60 * 60) | 0;
var appendMinute = currentTime % (1000 * 60 * 60) / (1000 * 60) | 0;
var appendSecond = currentTime % (1000 * 60) / 1000 | 0;
appendHour = appendHour < 10 ? "0" + appendHour : appendHour;
appendMinute = appendMinute < 10 ? "0" + appendMinute : appendMinute;
appendSecond = appendSecond < 10 ? "0" + appendSecond : appendSecond;
hour.html(appendHour);
min.html(appendMinute);
sec.html(appendSecond);
}
This code is work for anti-clockwise direction.I hope you get some idea from below example.
// Set the date we're counting down to
var countDownDate = new Date("July 5, 2019 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>
This code basically puts out a countdown. The problem is, i would like it to be put out as D/HH/MM/SS as for example 1 day 05 hours 20 minutes 02 seconds, but i'm pretty new to coding, so i wonder if somebody could show/help me what is the right way to do it.
Thanks in advance!
Blockquote
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Sorry, I did not read your answer carefully enough the 1st time.
Details here about padStart
a new language feature and an old work around (repeated below).
function pad(num, size) {
//num, string to be padded with leading zeros
//size, size of result after padding
//pads up to 10 characters
var s = "000000000" + num;
return s.substr(s.length-size);
}
var test='1';
console.log(pad('123456789',10)); //pads up to 10 char, result '0123456789'
console.log(pad(test,2)); //pads up to 2 char, result '01'
function countDown(){
// Set the date we're counting down to
var countDownDate = new Date("july 11, 2017 10:19:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
countDownDate = new Date("july 18, 2017 10:19:00").getTime();
}
}, 1000);
}
countDown();
what I want to reach is the every week the timer will start count to the next week.
I have something that start every week in the same day and in the same hour.
I don't want to rewrite the code every week :/
Thank you.
so why so much calculation is needed just to calculate how many seconds are remaining to start of next week? for example I am writing a sample code to calculate it.
function distranceToNextWeekStartInSeconds() {
var now = new Date()
var dayDiff = 7 - now.getDay();
var startOfNextWeek = new Date(now.valueOf());
startOfNextWeek.setDate(now.getDate() + dayDiff);
startOfNextWeek.setHours(0);
startOfNextWeek.setMinutes(0);
startOfNextWeek.setSeconds(0);
return Math.floor((startOfNextWeek - now) / 1000);
}
console.log('Seconds remaining to next week start: ' + distranceToNextWeekStartInSeconds())
and you can simply call this function inside your timer for a live calculation and display purpose, That's It.
I assumed you wanted to count down to every next tuesday at 10:19:00.
I'm too lazy right now to test every cases, ut I think it should work.
function getNextTuesday() {
// Get the date from now
var date = new Date();
// Set target hour/minute/seconds
date.setHours(10);
date.setMinutes(19);
date.setSeconds(0);
// Seek for the next tuesday
var actualDay = date.getDay();
var targetDay = 2; //Tuesday
// diff will give us the day span between today and the next tuesday
var diff = targetDay - actualDay;
// If the diff is less than 0 (we're sunday or monday, or we fall on the exact day, minutes after the target hour) then add a week
if (diff < 0 || (date.getTime() - new Date().getTime()) <= 0) {
diff += 7;
}
// Finally add the day span to the current date
date.setDate(date.getDate() + diff);
return date;
}
function countDown() {
// Set the date we're counting down to
var countDownDate = getNextTuesday();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (distance < 0) {
// If the count down is over, write some text
document.getElementById("demo").innerHTML = 'IT\'S HAPPENING !';
countDownDate = getNextTuesday();
} else {
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
}, 1000);
}
countDown();
<div id="demo"></div>