I am trying to make a countdown timer which displays the amount of time remaining for a customer to purchase in order to receive same day shipping.
For example, if they purchase before 15:30 the timer will say something like order within 30 minutes for shipping today (if it was 15:00).
However, when it reaches 15:30, I want it to say order within 23 hours and 59 minutes to receive shipping tomorrow. Then obviously when it reaches midnight it will turn to today. Alternatively it can just display the day/date so today/tomorrow won't matter.
I know I need to call the function again looking at tomorrows date but I'm not very handy with javascript so cannot figure it out.
Can someone help?
// Set the date we're counting down to
var nowDate = new Date();
var countDownDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 15, 30, 0, 0);
// 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 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"
if (hours >= 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " // date of shipment;
}
else if (hours < 1 && minutes < 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + seconds + "s "
+ "to have your order shipped on " // date of shipment;
}
else {
document.getElementById("shipping-countdown").innerHTML = "Order within " + minutes + "m "
+ seconds + "s " + "to have your order shipped on " // date of shipment;
}
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
// Start again but looking at tomorrows date
}
// If the count down is finished, write some text
if (nowDate.getDay() == 0 || nowDate.getDay() == 6) {
clearInterval(x);
document.getElementById("shipping-countdown").innerHTML = "Order within " + days + "d "
+ hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " // Start of the week;
}
}, 1000);
<!-- Display the countdown timer in an element -->
<p id="shipping-countdown"></p>
You don't need to clear the setInterval function. Just reset the new target date while keeping it alive. You also had some issues with the countdown going into the negatives which I fixed by moving the distance check and resetting the distance if it is under 1 second.
// Set the date we're counting down to
var nowDate = new Date();
var countDownDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 11, 2, 50, 0);
// 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;
if (distance < 1) {
countDownDate = countDownDate.setDate(countDownDate.getDate()+1);
distance = countDownDate - now;
}
// Time calculations for 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"
if (hours >= 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " // date of shipment;
}
else if (hours < 1 && minutes < 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + seconds + "s "
+ "to have your order shipped on " // date of shipment;
}
else {
document.getElementById("shipping-countdown").innerHTML = "Order within " + minutes + "m "
+ seconds + "s " + "to have your order shipped on " // date of shipment;
}
// If the count down is finished, write some text
if (nowDate.getDay() == 0 || nowDate.getDay() == 6) {
clearInterval(x);
document.getElementById("shipping-countdown").innerHTML = "Order within " + days + "d "
+ hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " // Start of the week;
}
}, 1000);
<!-- Display the countdown timer in an element -->
<p id="shipping-countdown"></p>
I have managed to achieve this with the following code, figured out I was along the wrong lines and could simply just adjust the countDownDate variable.
// Set the date we're counting down to
var nowDate = new Date();
var countDownDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 15, 30, 0, 0);
// 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 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 the count down is finished, write some text
if (countDownDate.getDay() == 6) {
countDownDate.setDate(countDownDate.getDate()+2);
}
if (days >= 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " + countDownDate;
}
else if (hours >= 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + hours + "h "
+ minutes + "m " + seconds + "s " + "to have your order shipped on " + countDownDate.getDate() + "/"
+ (countDownDate.getMonth()+1) + "/" + countDownDate.getFullYear();
}
else if (minutes >= 1) {
document.getElementById("shipping-countdown").innerHTML = "Order within " + minutes + "m " + seconds + "s "
+ "to have your order shipped on " + countDownDate.getDate() + "/"
+ (countDownDate.getMonth()+1) + "/" + countDownDate.getFullYear();
}
else {
document.getElementById("shipping-countdown").innerHTML = "Order within " + seconds + "s "
+ "to have your order shipped on " + countDownDate.getDate() + "/"
+ (countDownDate.getMonth()+1) + "/" + countDownDate.getFullYear();
}
// If the count down is finished
if (distance < 0) {
countDownDate.setDate(countDownDate.getDate()+1);
}
}, 1000);
<!-- Display the countdown timer in an element -->
<p id="shipping-countdown"></p>
Related
I made a countdown using javascript and php from my functions the countdown works but now I want to have 3 options:
if the countdown is longer than 24 hours show te selector.next(".countdown").html(expiry); date
if the countdown is 6 hours or less show the timer selector.next(".countdown").html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
else the countdown is less than 0 show that the endend selector.next(".countdown").html(<p>Closed</p>);
$(".expiry").each(function() {
var expiry = new Date($(this).text());
var selector = $(this)
var x = setInterval(function() {
var currentDateObj = new Date();
var numberOfMlSeconds = currentDateObj.getTime();
var addMlSeconds = 60 * 60 * 1000;
var now = new Date(numberOfMlSeconds - addMlSeconds);
var distance = expiry - now;
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 >= 86400000 && distance < 21600000){
selector.next(".countdown").html(expiry);
}else if ( distance <= 21600000 && distance > 0){
selector.next(".countdown").html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
}else{
selector.next(".countdown").html('<p>error</p>');
}
}, 1000);
});
Is the first line of your IF statement correct? Are you wanting to check if it's between those 2 numbers? If so, should the condition not be:
if(distance <= 86400000 && distance > 21600000)
I.E. If the distance is LESS THAN OR EQUAL TO 86400000 AND GREATER THAN 21600000
At the moment you're checking if distance is both GREATER THAN OR EQUAL TO 86400000 and LESS THAN 21600000 which will always produce false
EDIT
See full if statement block with condition for GREATER THAN 86400000
if (distance > 86400000) {
selector.next(".countdown").html('<p>A LOOOOOONG Way off expiring</p>');
}
else if (distance <= 864000000 && distance > 432000000) {
selector.next(".countdown").html(expiry);
}
else if (distance <= 432000000 && distance > 0) {
selector.next(".countdown").html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
}
else if (distance < 0) {
selector.next(".countdown").html('<p>afgelopen</p>');
}
else {
selector.next(".countdown").html('<p>Error</p>');
}
I'm having an issue making this countdown, it shows more hours than "23". Any idea how to fix it?
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
return days + " days" + " : " + hours + " hrs" + " : " + minutes + " min" + " : " + seconds + " sec";
};
let startTime = 1649303300; // database unix-timestamp value
setInterval(() => {
let curTime = (new Date()).getTime() / 1000;
curTime = parseInt(curTime);
if (curTime < startTime){
document.getElementById("timer1").innerText = ("LAUNCHING IN:");
document.getElementById("timer").innerText = (`${startTime-curTime}`).toHHMMSS();
}
else {
document.getElementById("timer1").innerText = ("LAUNCHED");
document.getElementById("timer").innerText = ("");
}
}, 1000);
"
I'm getting more than "23" for the "hours" variable instead of increasing the days every 24 hours.
You're not subtracting the days from the hours variable in the way that you're doing it for minutes and seconds. Try declaring your hours variable like this:
var days = Math.floor(sec_num / 86400);
var hours = Math.floor((sec_num - (days * 86400)) / 3600);
You can also use modular arithmetic to strip the excess values. You can use the modulo operator for this, e.g.
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600) % 24;
var minutes = Math.floor(sec_num / 60) % 60;
var seconds = sec_num % 60;
return days + " days" + " : " + hours + " hrs" + " : " + minutes + " min" + " : " + seconds + " sec";
};
I'm somewhat new to Javascript. Last year my countdown worked correctly. However, as soon Christmas hit, it started counting down to February 27 of the new year and I can't figure out why.
I tried moving some of the variables (year and countDownDate) and I also tried restarting countDownDate when I restart year. But since the year hasn't restarted I'm honestly not too sure if either of these worked.
var d = new Date();
var year = d.getFullYear();
// Set the date we're counting down to
var countDownDate = new Date("Dec 25, " + year + " 0:00:01").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 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 = ('0' + days).slice(-2) + "d " + ('0' + hours).slice(-2) + "h " + ('0' + minutes).slice(-2) + "m " + ('0' + seconds).slice(-2) + "s ";
// If the count down is over, restart timer to next Christmas
if (distance == 0) {
year = d.getFullYear() + 1;
}
}, 1000);
I would like it to countdown to Christmas each year. So then when Christmas hits it needs to begin the countdown for the next year.
I used the advice below from Tyler Roper and iagowp to make it work correctly! Showing the hundredths place for the days is very important.
You have a bug here:
('0' + days).slice(-2)
When days are bigger than 100, you are removing one of the chars, so if days = 349, it will become 49 days.
If you want to make sure it has at least double digits, you could replace it by
(days > 10 ? days : '0' + days) + "d " + ('0' + hours).slice(-2) + "h " + ('0' + minutes).slice(-2) + "m " + ('0' + seconds).slice(-2) + "s ";
Im setting up a new years countdown (bit late i know) but i would like to know how to get this to work for other timezones
I have already got it working for the usual UTC timezone as thats default. I have tried the .toLocalString and it returned NaN on the countdown
var countDownDate = new Date("Dec 31, 2018 23:59:02").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));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("display").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("display").innerHTML = "Happy New Year!";
done()
}
}, 1000);
The Date function of javascript returns local time of each timezone depending from where the page is loaded. So you don't have to keep track of each timezone
explained here
You can achieve this with moment.js easily:
var tz = moment.tz.guess();
console.log("Current Timezone: " + tz);
var last = moment.tz("2018-12-31 23:59:02", tz);
setInterval(function(){
var current = moment.tz(tz);
if(current.isBefore(last, "seconds")){
var diff = moment.duration(last.diff(current));
document.getElementById("display").innerHTML = diff.days() + "d " +
diff.hours() + "h " + diff.minutes() + "m " + diff.seconds() + "s";
}else{
document.getElementById("display").innerHTML = "Happy New Year!";
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
<div id="display"></div>
I'm trying to make a dynamic time counter/timer in JavaScript.
Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.
In case the timestamp is less than a day I would like that the script dynamically displays only the hours.
1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE
Here is the code I try to make it work.
<center>
<script>
var countDownDate = new Date("2017-11-17T20:10:30Z").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
// Seconds
if (distance < 1000){
document.getElementById("count1").innerHTML = seconds + "s ";
}
// Minutes
if (distance < 60000){
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
}
// Hours
if (distance < 3600000){
var hours = Math.floor(distance / (1000 * 60 * 60 * 1));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
}
// Days
if(distance > 3600001){
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);
document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " $
}
if (distance < 0) {
clearInterval(x);
document.getElementById("count1").innerHTML = "You will be redirected now";
}
}, 1000);
</script>
<p id="count1"></p>
</center>
I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.
These changes made it work for me:
<center>
<script>
var countDownDate = new Date("2017-11-17T21:30:30Z").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));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Seconds
if (distance <= 60000) {
document.getElementById("count1").innerHTML = seconds + "s ";
}
// Minutes
else if (distance <= 3600000) {
document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
}
// Hours
else if (distance <= 86400000) {
document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
}
// Days
else if (distance > 86400000) {
document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
if (distance < 0) {
clearInterval(x);
document.getElementById("count1").innerHTML = "You will be redirected now";
}
}, 1000);
</script>
<p id="count1"></p>
I changed the milliseconds accordingly, and in your days you had a "$" so i changed that.
I changed the date around and got the effect I think you were going for.
It looks like you're doing this the absolute hardest way possible, and also reinventing the wheel. There are a lot of great references to built in javascript functions (like MDN) that you should really take a look at.
If you're doing this as an intellectual exercise think about restructuring your code into something like this (obviously just psuedocode):
let dateHTML = "";
if (time1.seconds - time2.seconds > 0) {
dateHTML = (time1.seconds - time2.seconds) + "s";
}
if (time1.minutes-time2.minutes > 0) {
dateHTML = (time1.minutes-time2.minutes) + "m " + dateHTML;
}
//So on and so forth for the maximum interval you want to account for.
document.getElementById("count1").innerHTML = dateHTML;
You can probably get really clever with null operators, putting the time unit distances into an array to clean up the syntax and avoid doing calculations twice etc. but this should cut down on what you're doing significantly.
Do keep in mind that there are JS libraries built to do this exact sort of thing really well, so if you're working on a "real" project consider that.
Here is the whole script in working order in case somebody else need it:
The whole script is meant to be reused multiply times in a single page by changing the ID in the $FD['id'] array variable and copy pasting the function that prints/echoing the function content.
PHP FUNCTION INCLUDE FILE (count.php):
<?php
// JS Date format
// 2017-11-14T12:00:00Z
function counter($FD){
$date=$FD['date'];
$id=$FD['id'];
$display_start_1=$FD['display_start_1'];
$display_start_2=$FD['display_start_2'];
$display_end=$FD['display_end'];
echo $counter=<<<a
<center>
<script>
var countDownDate$id = new Date("$date").getTime();
var x$id = setInterval(function () {
var now$id = new Date().getTime();
var distance$id = countDownDate$id - now$id;
var days$id = Math.floor(distance$id / (1000 * 60 * 60 * 24));
var hours$id = Math.floor((distance$id % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes$id = Math.floor((distance$id % (1000 * 60 * 60)) / (1000 * 60));
var seconds$id = Math.floor((distance$id % (1000 * 60)) / 1000);
// Seconds
if (distance$id <= 60000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + seconds$id + "s " + " $display_start_2";
}
// Minutes
else if (distance$id <= 3600000) {
document.getElementById("count$id").innerHTML ="$display_start " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
// Hours
else if (distance$id <= 86400000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
// Days
else if (distance$id > 86400000) {
document.getElementById("count$id").innerHTML ="$display_start_1 " + days$id + "d " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
}
if (distance$id < 0) {
clearInterval(x$id);
document.getElementById("count$id").innerHTML = "$display_end";
}
}, 1000);
</script>
<p id="count$id"></p>
a;
}
?>
PHP DISPLAY FILE (count_display.php):
<?php
$now = time();
// Simulation of utc time (-1 hour +1 minute)
// By modifying the amount of seconds you set/define the amount of seconds that will counted down
$timestamp_new=$now-3600+10;
// Time formattig for JavaScript code
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);
// Include the function file once only
include'count.php';
// Define variables for the first counter
$FD1['date']="$date_new";
$FD1['id']='1';
$FD1['display_start_1']="Please wait for another:<br >";
$FD1['display_start_2']="<br />We are preparing your playground for you.";
$FD1['display_end']="Your Playground is ready at:<br /><a href='http://555.555.555.555'>Game server 01</a>";
counter($FD1);
// Define variables for the second counter
$timestamp_new=$now-3600+15;
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);
// The second count down timer
$FD2['date']="$date_new";
$FD2['id']='2';
$FD2['display_start_1']="Please wait for another:<br >";
$FD2['display_start_2']="<br />We are preparing your playground for you.";
$FD2['display_end']="Your Playground is ready at:<br /><a href='http://100.100.100.100'>Game server 02</a>";
counter($FD2);
// And so on ....
?>
Hoping that this will save a lot of time to somebody else ;)
Have a great life (you who can and know how) ;)