我有点困惑。我需要每月的1号开始计算3天。等到到期时间重新开始。
var today = new Date(),
end = new Date( today.getFullYear(), today.getMonth(), today.getDate() + 3 );
var timer = setInterval(function() {
var differenceTime, dd, hh, mm, ss, str;
if ( ( new Date().getDate() == end.getDate() ) || ( new Date().getDate() == 1 ) ) {
end = new
} else {
differenceTime = end - new Date();
dd = parseInt(differenceTime / (1000 * 60 * 60 * 24));
hh = parseInt(differenceTime / (60 * 60 * 1000)) % 24;
mm = parseInt(differenceTime / (1000 * 60)) % 60;
ss = parseInt(differenceTime / 1000) % 60;
document.querySelector('.days').innerHTML = format(dd);
document.querySelector('.hours').innerHTML = format(hh);
document.querySelector('.minutes').innerHTML = format(mm);
document.querySelector('.seconds').innerHTML = format(ss);
}
}, 1000);
function format(num) {
return (9 < num) ? num : "0" + num;
};
<div class="cowntdown">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
<div class="cowntdown">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
帮助做出正确的条件。
最佳答案
我试图重用尽可能多的代码。如果我正确理解了您的问题,这应该可以解决问题。
如果使用moment.js,则可能会得到一些更简洁的代码,尤其是在格式化文本和计算日期之间的差异时。
请记住,该检查并不完全准确,因为它会比较日期(秒)以内。
var numberOfDays = 3;
var today = new Date();
var start = getNextStartDate(today);
var end = getNextEndDate(today);
var timer = setInterval(function() {
var differenceTime, dd, hh, mm, ss, str;
var now = new Date();
if (now >= end) {
start = getNextStartDate(now);
end = getNextEndDate(now);
} else {
differenceTime = end - now;
dd = parseInt(differenceTime / (1000 * 60 * 60 * 24));
hh = parseInt(differenceTime / (60 * 60 * 1000)) % 24;
mm = parseInt(differenceTime / (1000 * 60)) % 60;
ss = parseInt(differenceTime / 1000) % 60;
document.querySelector('.days').innerHTML = format(dd);
document.querySelector('.hours').innerHTML = format(hh);
document.querySelector('.minutes').innerHTML = format(mm);
document.querySelector('.seconds').innerHTML = format(ss);
}
}, 1000);
function getNextEndDate(fromDate) {
return new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate() + numberOfDays);
}
function getNextStartDate(currentDate) {
var currentDay = currentDate.getDate();
var index = Math.ceil(currentDay / 3);
var nextStartDay = 1 + numberOfDays * index
return new Date(currentDate.getFullYear(), currentDate.getMonth(), nextStartDay);
}
function format(num) {
return (9 < num) ? num : "0" + num;
};
<div class="cowntdown">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
如果您愿意,也有一个jsfiddle
关于javascript - 每3天倒数计时器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36352088/