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>
Related
I have ecommerce website. In that for same day delivery need to order before 11. So before 30 minutes of the end time(i.e. 11) i want to show that timer section.
Below code I am trying But getting issue how to set timer functionality.
setInterval(function(){
var secs = 1800;
var date = new Date;
// date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
console.log("Hour"+hour+"Minutes"+minutes+"seconds"+seconds);
// console.log(minutes);
// console.log(seconds);
if(hour == 10 && minutes>=30)
{
var mins = secs / 60;
console.log("Timer"+mins);
$('.top-header-content1').removeClass('hide-ticker1');
}
else if (hour >= 11){
console.log("hii11");
$('.top-header-content1').addClass('hide-ticker1');
}
secs--;
},1000);
If anyone have a idea , how to add time please let me know
Hi you use this code below:
/// the counting date
var countDownDate = new Date("Jan 5, 2024 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);
// 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
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
The following code will start a setInterval() in which during a time window between 10:30h and 11:00h a countdown will be shown. Before 10:30h and after 11:00h different messages are shown. And after 11:00h the setInterval is cleared.
// div for output on page:
const demo=document.getElementById("demo"),
// today's date
today = new Date();
today.setHours(11);today.setMinutes(0);today.setSeconds(0);
today.intv=setInterval(checkTime,1000);
function checkTime(){
const now=new Date();
if (now>today) {
demo.textContent="Order today for tomorrow's delivery.";
clearInterval(today.intv);
}
else if (now>(today-1800000)){
let tsec=Math.floor((today-now)/1000),
sec=tsec%60,
min=(tsec-sec)/60;
demo.textContent=`${min} minutes and ${sec} seconds left if you want to order for today's delivery.`;
} else
demo.textContent="Order now for today's delivery!"
}
<p id="demo"></p>
I have the following javascript code:
function t5am() {
// Set the date we're counting down to
// Year, Month ( 0 for January ), Day, Hour, Minute, Second, , Milliseconds
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::: 5:00 AM ::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// (AAAA,MM,DD,HH,mm,S));
var countDownDate = new Date(Date.UTC(2020,05,29,12,00,00));
// 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
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
// 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"
for (const ele of document.getElementsByClassName("t5am")){
ele.innerHTML = (days + "<span>d</span> " + hours + "<span>h</span> "
+ minutes + "<span>m</span> " + seconds + "<span>s</span><br />")
}
// If the count down is over, write some text
if (distance < 0) {
for (const ele of document.getElementsByClassName("t5am")) {
ele.innerHTML = "<p class='live-text'>Live</p> ";
}
if (distance + 7200000 < 0){
ele.innerHTML = "Ended";
}
}
}, 1000);
}
t5am()
It is a counter that works fine for me, but now I want to do a double "if" function.
When the counter reaches zero, then it shows "Started".
I need that in addition to that, after 2 hours after "Started", it shows "Ended"
How can I do it?
This is how you can do this:
Just need add two more hours to your current time which i have done below and then check if distance + twoHours < 0 to show 'Ended' Message
Also, you have to clearInterval(x) as well i will leave that for you to clear when you want after the condition have been met and it is ended.
Remember: Its NOT ideal to use setTimeout for this because if the user leave the page and come page the setTimeout funtion will start from 2 hours again which is not ideal in your case you want to stop it exactly after 2 hours to when its was started which will be in real time regardless of user staying on the browser / screen or not.
Just to make some correction on using innerHTML as well. Its is not rec-emended to user innerHTML at all. I have used textContent which is exactly the same.
InnerHTML is not rec-emended officially by javascript MDN . You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML why its not good to use innerHTML to change text in elements.
Recreated Demo: https://jsfiddle.net/bv0odyqr/1/
Try this code and should work just fine.
function t5am() {
// Set the date we're counting down to
// Year, Month ( 0 for January ), Day, Hour, Minute, Second, , Milliseconds
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::: #1 ::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// (AAAA,MM,DD,HH,mm,S));
var countDownDate = new Date(Date.UTC(2020, 05, 27, 20, 20, 0));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
const twoHours = new Date();
twoHours.setHours(twoHours.getHours() + 2);
var two = twoHours.getTime()
// Find the distance between now an the count down date
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
//Results div
var result = document.getElementsByClassName("t5am")[0];
// 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.getElementsByClassName("t5am")[0].textContent = days + "<span>d</span> " + hours + "<span>h</span> " +
minutes + "<span>m</span> " + seconds + "<span>s</span><br />";
// If the count down is over, write some text
if (distance < 0) {
result.textContent = "Started";
} else if (distance + twoHours < 0) {
result.textContent = "Ended";
}
}, 1000);
}
t5am()
<div class="t5am"></div>
I was following this tutorial: https://www.w3schools.com/howto/howto_js_countdown.asp
And everything works except for timezones, I want it to show the same time on every device, no matter the timezone, in UTC. How would I go about this?
If someone in a timezone was ahead of me, they would see a different time (because they are an hour ahead, so the countdown would end at a different time. It would end for them an hour ahead of when it ends for me, I want the same time on the timer to be shown everywhere
Code (Edited):
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
function getUTCNow() {
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
// Set the date we're counting down to
//var countDownDate = new Date("Sep 15, 2018 15:00:00").getTime();
var countDownDate = new Date("Sep 7, 2018 20:00:00");
var countDD = convertDateToUTC(countDownDate);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
var nowUTC = now.getUTCTime();
// Find the distance between now and the count down date
var distance = countDD.getTime() - nowUTC.getTime();
// 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="timer"
document.getElementById("timer").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("timer").innerHTML = "RELEASED!";
}
}, 1000);
<div id="timer"></div>
I managed to display a countdown timer in H:M:S format.
May I know how can I display it to HH:MM:SS format? Example, let's say for 300 hours, 1 minute and 1 second, it will display as 300:01:01 instead of 300:1:1 .
This is what I got so far.
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55: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 and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (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 = hours + " : "
+ minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
Test for values less than 10 and append a leading zero
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55: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 and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) hours = '0'+ hours;
if (minutes < 10) minutes = '0'+ minutes;
if (seconds < 10) seconds = '0'+ seconds;
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + " : "
+ minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
As kamoroso94 mentioned in a comment, you could also use padstart()
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55: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 and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (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 = hours.toString().padStart(2, '0') + " : "
+ minutes.toString().padStart(2, '0') + " : " + seconds.toString().padStart(2, '0') + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
You can prefix(aka padLeft) the hours, minutes and seconds with arbitrary length strings as below:
function padLeft(padding, data) {
return +(padding + data).slice(-padding.length);
}
padLeft('00', 3) // '03'
padLeft('00', 13) // '13'
padLeft('0000', 3) // '0003'
You can do this with a simple replace:
var timeString = (hours + ':' + minutes + ':' + seconds).replace(/\b(\d)\b/g, '0$1');
EDIT: in case you do not want to prepend a zero to the hours:
var timeString = (hours + ':' + minutes + ':' + seconds).replace(/:(\d)\b/g, ':0$1');
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55: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 and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = (`0${Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))}`).substr(-2); ;
var seconds = (`0${Math.floor((distance % (1000 * 60)) / 1000)}`).substr(-2);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = `${hours}:${minutes}:${seconds}`;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
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>