jQuery倒计时器不倒计时

时间:2015-07-13 09:18:26

标签: javascript jquery timer countdown

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

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

我的实际代码行是这样的

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

我改变了小提琴,以便像这样轻松理解

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

1 个答案:

答案 0 :(得分:2)

要从字符串中获取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