Reputation: 1538
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>
Upvotes: 1
Views: 737
Reputation: 87203
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
EDIT
Also change the way you're getting date from server. Wrap it in quotes.
var then = '<?php echo $server_response; ?>'; // String
Upvotes: 2