I am trying to implement a countdown timer using jQuery. I have an end time and the timer should count down from it until the current time becomes same as it.
I get the end time from a web service which I fetch using PHP an the end time that I get looks like this 2015-07-15 17:29:31.
My actual line of code is like this
var then=<?php echo $server_response; ?>;
which I changed in the fiddle for easy understanding like this
var then='2015-07-15 17:29:31';
Here's the JavaScript code:
var timer;
var then='2015-07-15 17:29:31';
var now = new Date();
//now.setDate(now.getDate() + 7);
var compareDate=then.getDate()-now.getDate();
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
HTML
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>
Fiddle
To get the date from string use new Date(date).
See the changes:
var compareDate = new Date(then) - now.getDate();
// ^^^^^^^^^^^^^^ instead of then.getDate()
In timeBetweenDates()
var dateEntered = new Date(toDate);
// ^^^^^^^^^^^^^^^^^ Parse to date instead of using it as it is
Demo
EDIT
Also change the way you're getting date from server. Wrap it in quotes.
var then = '<?php echo $server_response; ?>'; // String
Related
I'm trying to display the countdown timer between an enddate/time column and the system date/time column using below code. It's not displaying the timer.
I have created a page item P3_TIMER and it has a column P3_STARTDATE.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
$s('P3_TIMER',timer);
}
It's not possible to mix pl/sql and javascript. They're different languages and run in different environments.
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE; >>> This is pl/sql
var now = new Date();
The P3_STARTDATE needs to be converted to a javascript date object. That cannot be directly, some parsing is needed as shown in this thread.
For the example below the assumption is made that the date is passed in format DD-MON-YYYY.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function parseDate(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var p = s.split('-');
return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}
function timeBetweenDates(toDate) {
var dateEntered = parseDate(apex.item( "P63_DATE" ).getValue() );
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
apex.item("P63_TIMER").setValue(`Days: ${days}, Hours: ${hours}, Minutes: ${minutes}, Seconds: ${seconds}`);
}
I'm working on a countdown timer and I have this piece of code right now. I took it from a different post and modified it a bit. I probably don't have to explain how the script works but here is the way I want it to work:
Set a startdate and enddate in the html attributes.
Pass that data into two variables 'dataStart' and 'dataEnd'.
Use the 'dataStart' as startdate and use the 'dataEnd' as enddate.
Countdown from startdate to enddate like this:
If the startdate is in the future, don't start the countdown yet but
let it start as soon as the startdate = the currentdate.
If the startdate is in the past, start the countdown but display the amount
of days, hours, minutes and seconds left from the currentdate to the
enddate.
var dataEnd = document.getElementById('countdown').getAttribute("data-end");
var dataStart = document.getElementById('countdown').getAttribute("data-start");
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
var tiles = document.getElementById('tiles');
var tilesClass = document.getElementById('tiles').classList;
var countLabel = document.getElementById('countdown-label');
var countDiv = document.getElementById('countdown');
function showRemaining() {
var end = new Date(dataEnd);
var start = new Date();
var distance = end - start;
if (distance < 0) {
clearInterval(timer);
// Replaces the countdown tiles with '---' & the label with 'SALE IS OVER'.
tiles.innerHTML = '---';
countLabel.innerHTML ='SALE IS OVER!';
// Sets display to none, so when the countdown is finished it will NOT be visible anymore.
countDiv.style.display = 'none';
return;
} if (distance < _hour ) {
// Removes the Orange background and adds the Red background.
tilesClass.remove('color-half');
tilesClass.add('color-empty');
countLabel.innerHTML ='HURRY! SALE ENDS IN:';
} else {
// Sets display to block, so when the countdown is NOT finished it will be visible.
countDiv.style.display = 'block';
}
var days = pad(Math.floor(distance / _day));
var hours = pad(Math.floor((distance % _day) / _hour));
var minutes = pad(Math.floor((distance % _hour) / _minute));
var seconds = pad(Math.floor((distance % _minute) / _second));
tiles.innerHTML = days + ':';
tiles.innerHTML += hours + ':';
tiles.innerHTML += minutes + ':';
tiles.innerHTML += seconds + '';
}
timer = setInterval(showRemaining, 1000);
function pad(n) {
return (n < 10 ? '0' : '') + n;
}
I have basic javascript knowledge but can't figure this out myself...
I am using an API that returns the time like this deal_expiration_time:1469396377 which looks like its seconds from 1970. I am trying to get a countdown in MM/SS This is in angular so I apparently can't use jQuery? I have struggled for a while and am stumped with this code. I'm trying to make it so its input: 1469396377 | output: 08:21
function(){
var x1, secs1 = 510;
x1 = setInterval(function(){myFunc1(9)}, 1000);
function myFunc1(timerId){
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'+timerId).html(minutes + ':' + seconds); //assuming there is a label with Id 'timer'
secs1--;
if(secs1 == 0){
document.getElementById('timer_' + timerId).style.hidden = true;
clearInterval(x1);
}
}
}
You can get the current time using Date.now() and then manually calculate the difference in time. This function gets the difference between the given time and the current time, calculates the difference in seconds and in minutes. This difference is then formatted as a countdown string and then returned.
function getTimeDifference(expirationTime) {
var now = Date.now();
var diff = expirationTime - now;
var secDiff = Math.round(diff/1000);
var minDiff = Math.round(secDiff / 60);
var diffStr = minDiff + ":" + (secDiff - minDiff * 60);
return diffStr
}
lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).
I have this chunk of javascript that's kind of hacked around from http://www.developphp.com/view.php?tid=1248 and I am seeing an error of "undefined variable - broadcast".
function cdtd(broadcast) {
/* expected date format is Month DD, YYYY HH:MM:SS */
var nextbroadcast = new Date(broadcast);
var now = new Date();
var timeDiff = nextbroadcast.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.getElementById("countdown").innerHTML = "<a href=\"flconlineservices.php\">Internet broadcast in progress<\/a>";
/* Run any code needed for countdown completion here */
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days + " d";
document.getElementById("hoursBox").innerHTML = hours + " h";
document.getElementById("minsBox").innerHTML = minutes + " m";
// seconds isn't in our html code (javascript error if this isn't commented out)
/*document.getElementById("secsBox").innerHTML = seconds + " s";*/
var timer = setTimeout('cdtd(broadcast)',1000);
}
"broadcast" is passed from the page with this <script type="text/javascript">cdtd("<?php echo $nextbroadcast; ?>");</script>. $nextbroadcast is based upon the date/time when the user views the page.
I tried var broadcast;, var broadcast = "";, and var broadcast = null;. Whenever I try to declare the variable, before the function, it breaks the script.
Am I doing something incorrectly? The script is working, just fine, but I'd rather not have the error.
Change the following line:
var timer = setTimeout('cdtd(broadcast)',1000);
To this:
var timer = setTimeout(function() { cdtd(broadcast); }, 1000);
This might be where the problem is:
var timer = setTimeout('cdtd(broadcast)',1000);
You should declare var timer; above cdtd() function, and then set it like so below or outside of the function:
var func = 'cdtd(' + broadcast + ')';
timer = setTimeout(func,1000);