I am trying to code a count down timer in Vanilla Javascript. Below is the code:-
var futureDate = new Date("oct 31,2021 10:00:00").getTime();
var currentDate = new Date().getTime();
var diffTime = futureDate - currentDate;
console.log(diffTime);
var days = Math.floor(diffTime / (1000* 24* 60*60));
console.log(days);
var hours = Math.floor(diffTime / (1000 * 60 * 60));
console.log(hours);
var minutes = Math.floor(diffTime / (1000 * 60));
console.log(minutes);
var seconds = Math.floor(diffTime / (1000));
console.log(seconds);
Below is the output of the code provided in the console.
This output is in accordance with below image
But I am failing to understand the particular code written in w3schools as highlighted in blue color in the image below
I am not able to figure out the difference between 2 code written?
Date.getTime() returns the number of milliseconds since the Unix epoch (1900-01-01 00:00:00).
When you subtract the time between 2 dates, you will get the time difference in milliseconds. In your code, you are showing
The total number of hours between the dates
The total number of minutes between the dates
The total number of seconds between the dates
Let's take the number of hours as an example, the code written in w3schools takes the remainder from dividing the time difference by the number of milliseconds per day. This way, you will get the time difference in less than 24 hours and you can use it to calculate the time difference in hours.
Do the same for the minutes and seconds and you will get the same result written in w3schools
var futureDate = new Date( "oct 31,2021 10:00:00" ).getTime();
var currentDate = new Date().getTime();
var timeDiffInMilliseconds = futureDate - currentDate;
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60; // 1000 * 60
var millisecondsPerHour = millisecondsPerMinute * 60; // 1000 * 60 * 60
var millisecondsPerDay = millisecondsPerHour * 24; // 1000 * 60 * 60 * 24
console.log( 'timeDiffInMilliseconds: ' + timeDiffInMilliseconds );
var days = Math.floor( timeDiffInMilliseconds / millisecondsPerDay );
console.log( 'days: ' + days );
var timeDiffInLessThan1Day = timeDiffInMilliseconds % millisecondsPerDay;
var hours = Math.floor( timeDiffInLessThan1Day / millisecondsPerHour );
console.log( 'hours: ' + hours );
var timeDiffInLessThan1Hour = timeDiffInMilliseconds % millisecondsPerHour;
var minutes = Math.floor( timeDiffInLessThan1Hour / millisecondsPerMinute );
console.log( 'minutes: ' + minutes );
var timeDiffInLessThan1Minute = timeDiffInMilliseconds % millisecondsPerMinute;
var seconds = Math.floor( timeDiffInLessThan1Minute / millisecondsPerSecond );
console.log( 'seconds: ' + seconds );
Okay, first you need to understand the basic concept of dates in vanilla javascript.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
1 day = 24 hours
Math.floor is simply used for returning the highest rounded value possible.
Now coming to your question,
var distance = countDownDate - now;
This line basically takes two UNIX format date integers and gives you the difference in the form of unix timestamp. So once you get the difference you need to find out how many hours, minutes and days it comprises of, and that's just it.
We use the simple formulas I mentioned to top to identify just that.
1000 * 60 * 60 * 24 is 1 day
So we divide the total difference in two dates by the 1 day to get the number of days in total with the following line:
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
Similarly, with the code below, we take the difference in two dates and first get the number of days from it and then whatever time remains we use that time to further calculate the hours by dividing the value by (1000 * 60 * 60).
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
The following line first calculates the number of hours from the difference and then whatever remains is then further divided by a minute to get the totals minutes remaining. Similarly, concept will be applied to calculate the seconds.
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
Related
This code for a countdown timer is taken from W3Schools:
// Set the date we're counting down to
var d = new Date();
var n = d.getTimezoneOffset() * 60000;
var countDownDate = new Date("May 2, 2018 15:54: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 - n;
// 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);
There was a big issue with it: any date I enter would not work for different timezones, as if it was +1 hour UTC it would expire, and it would be an hour long if it was -1.
So I added the d.getTimezoneOffset() * 60000; to get the milliseconds difference, and then took it off, so if there is any difference it should calculate it.
Will it always work if I put an UTC date in the future, or is there a possible difference I don't know about (for example a special country or daylight savings that could mess it up)?
i can image someone had donde this already or it can be considered a duplicated question, i've been searching for weeks and i can't figure out how to accomplish this.
I have a countdown made in js, the problem i'm facing is that when ever i test it in another country the times throw out different hours example.
i'm in centralamerica, end date is apr 16, 2018 23:59:59" if i test this in centralamerica it says 6 days and 10 hours remaining, if i run this in italy for example it says 6 days and 3 hours remaining, i need it to be equal all the time and that the timezone doesn´t affects, is this even possible, and please help on how to get it done.
the script i have is working but not the way i need to, i have a promo that will expire on "apr 16, 2018 23:59:59" so if it only has 5 hours remaining it shout say 5 hours remaining no matter where its been seeing from, but that is not happening.
$("#masterslider").append("<p id='demo'>.</p>")
$("#masterslider").append("<span> remaining time </span>")
//******************************** update date here ************************
var serverDate = new Date("apr 16, 2018 23:59:59");
var offset = serverDate.getTimezoneOffset();
serverDate = addOffset(serverDate, offset);
setInterval(function(){
updateCountdown();
}, 1000);
function addOffset(date, offset) {
var time = date.getTime() ;
return new Date(time + offset * 6000);
}
function updateCountdown() {
var userDate = new Date();
var distance = serverDate.getTime() - userDate.getTime();
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(serverDate.getTime() > userDate.getTime()){
$('#demo').html( days +"day(s)"+ " / " + hours + "hour(s)" + minutes + "minutes(s)");
}
else
{
$("#demo").html(mas);
$("#masterslider span").hide();
}
}
</script>
I've checked and setting correct timezone for "event timestamp" works for me regardless local client timezone I use.
let targetDate = new Date("2018-04-11 23:59:59 GMT-0800");
let refreshDelayMs = 1000;
function updateCounter() {
let distance = (targetDate - new Date()) / 1000;
let seconds = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let minutes = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let hours = Math.floor(distance % 24).toString().padStart(2, '0');
let days = Math.floor(distance / 24).toString().padStart(2, '0');
document.querySelector('.counter').innerHTML = `${days} days ${hours}:${minutes}:${seconds}`;
setTimeout(updateCounter, refreshDelayMs);
}
updateCounter();
Remains: <span class="counter"></span>
You can use moment-timezone from CDN or use NPM
repl.it sample
const moment = require("moment-timezone");
function toTimeZone(time, offset) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).utcOffset(offset).format(format);
}
toTimeZone("2018/04/10 15:37", "+0730")
I am trying to make a Countdown Timer in javascript and I wrote a code like
var countdown = function(){
setInterval(function() {
var countDownDate = new Date(document.getElementById("end_date").getAttribute("data-date")).getTime();
// data-date ex. = "2017-11-28 21:54:00"; greater than current date (now)
// 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"
if(hours<10){
hours = "0"+hours;
}
if(minutes<10){
minutes = "0"+minutes;
}
if(seconds<10){
seconds = "0"+seconds;
}
var left = hours + ":"+ minutes + ":" + seconds;
console.log(left);
document.getElementById("time_left").innerHTML = left;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time_left").innerHTML = "EXPIRED";
}
}, 1000);
}
countdown();
Counter is working fine but why I am getting difference of time upto 25 secs on different systems. Some systems shows same countdown time but, some not.
you should use your sever time and java script take the system time so when u change your system time count down will change automatically. you can also provide me your code using js fiddle or anything else...
My system time is UTC + 0 as I am in the UK.
My Script:
<script>
// Set the date we're counting down to
var countDownDate = new Date("<?php echo $date ?>").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("time").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time").innerHTML = "EXPIRED";
window.location.href = "/error";
}
}, 1000);
</script>
My PHP will echo a date + 15 minutes gotten from the serverside, a users order will expire after 15 minutes you see.
So here is a date that the countdown timer would use (2017-11-23 22:50:18) this would be 15 minutes from now, but is UTC + 0 time.
If the users system time was in another country or behind then it would expire and go to the error page straight away.
How would I convert this time to the users timezone (And even if they refresh the page the timer would still be counting down)
The PHP var for $date is gotten from the database and is laid out like so: "2017-11-23 22:50:18"
How do I convert this to the system time of the user?
I hope you understand me, thanks very much! :)
I have my countdown function (that works).
// Set the date we're counting down to
var countDownDate = new Date("<?= $stop_datejs ?>");
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
// 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) {
clearInterval(x);
document.getElementById("demo").innerHTML = "ACTUALIZA LA PÁGINA";
}
}, 1000);
But I need to compare with a php variable $actual_date (server date)
// Get todays date and time
var now = new Date("<?= $actual_date ?>");
That works but stops updating every second. What is the problem?
Thanks
The variable now will not be updated, because the variable will only be written once. So if you load the the webpage the value will be set once but not updated, because the website does not update again (Only your interval).
To provide this you can simply use:
// Get todays date and time
var now = new Date();
This will only use the current time for the new instance of Date. If your <?= $actual_date ?> is not the current timestamp or you want to sync if for all browsers/pc with an incorrect time setting you should have a look at AJAX. Using AJAX is the easiest way to get the updated time from the backend.
jQuery Ajax:
http://api.jquery.com/jquery.ajax/