jQuery 倒数计时器不倒计时

jQuery countdown timer does not count down

我正在尝试使用 jQuery 实现倒数计时器。我有一个结束时间,计时器应该从它开始倒计时,直到当前时间与它相同。

我使用 PHP 从 Web 服务获取结束时间,我得到的结束时间看起来像这样 2015-07-15 17:29:31

我实际的代码行是这样的

var then=<?php echo $server_response; ?>;

为了便于理解,我在 fiddle 中进行了更改

var then='2015-07-15 17:29:31';

这是 JavaScript 代码:

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

要从字符串中获取 date,请使用 new Date(date)

查看变化:

var compareDate = new Date(then) - now.getDate();
//                ^^^^^^^^^^^^^^ instead of then.getDate()

timeBetweenDates()

var dateEntered = new Date(toDate);
//                ^^^^^^^^^^^^^^^^^ Parse to date instead of using it as it is

Demo

编辑

同时更改您从服务器获取日期的方式。 用引号引起来。

var then = '<?php echo $server_response; ?>'; // String