Javascript / PHP倒数计时器,每秒更新一次并计入特定日期和时间

时间:2015-05-13 17:55:07

标签: javascript php jquery

所以下面的代码是我到目前为止能够使用的代码;但是,并没有完全按照我的需要去做。

我希望能够调用一个函数(又名:sundayDelta()),但是,我希望能够定义星期几和时间我希望函数在调用内的倒计时中使用功能。我不确定这是否可能......但我在想这样的事情

sundayDelta(1,1000)将变成星期日和星期几:1000(上午10:00)。不确定这样的事情是否可能;但是,我希望它是。我计划在同一页面上进行多次倒计时,只是在一天中的不同时间出现。

当倒计时结束时,我希望它刷新div(与div有什么名称无关)

我也希望能够将PHP服务器时间整合到这里,这样每个人都能看到正确的倒计时,无论他们身在何处。

任何帮助都会很棒!感谢您的投入!

function plural(s, i) {
  return i + ' ' + (i > 1 ? s + 's' : s);
}

function sundayDelta(offset) {
  // offset is in hours, so convert to miliseconds
  offset = offset ? offset * 20 * 20 * 1000 : 0;
  var now = new Date(new Date().getTime() + offset);
  var days = 7 - now.getDay() || 7;
  var hours = 10 - now.getHours();
  var minutes =  now.getMinutes() - 00 ;
  var seconds =  now.getSeconds()- 00;
    if (hours < 0){
      days=days-1;
    }
    var positiveHours= -hours>0 ? 24-(-hours) : hours;
  return [plural('day', days),
          plural('hour', positiveHours),
          plural('minute', minutes), 
          plural('second', seconds)].join(' ');
}

// Save reference to the DIV
$refresh = $('#refresh');

$refresh.text('This page will refresh in ' + sundayDelta());

// Update DIV contents every second
setInterval(function() {
  $refresh.text('This page will refresh in ' + sundayDelta());
}, 1000);

1 个答案:

答案 0 :(得分:1)

当我为间隔制作灵活的文本时,我喜欢减去直到没有剩下的东西。这样你只显示非0值:

function sundayDelta(target_date) {
    var now = new Date();
    var offset = Math.floor((Date.parse(target_date) - now.valueOf()) / 1000);

    var r = [];
    if (offset >= 86400) {
         var days = Math.floor(offset / 86400);
         offset -= days * 86400;
         r.push(plural('day', days));
    }
    if (offset >= 3600) {
         var hours = Math.floor(offset / 3600);
         offset -= hours * 3600;
         r.push(plural('hour', hours));
    }
    if (offset >= 60) {
         var minutes = Math.floor(offset / 60);
         offset -= minutes * 60;
         r.push(plural('minute', minutes));
    }
    if (offset != 0) {
         r.push(plural('second', offset));
    }
    return r.join(' ');
}

在PHP代码中,您可以通过这种方式设置变量。我们暂时将时区留出来,但也可以通过指定它们来添加它们。

echo "target_date = '" . date('Y-m-d H:i:s', strotime('next Sunday 10am')) . "';\n";