我有点困惑。我需要在本月的第一天开始计算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;
};
&#13;
<div class="cowntdown">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
&#13;
<div class="cowntdown">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
&#13;
帮助创造正确的条件。
答案 0 :(得分:1)
我尝试尽可能多地重用您的代码。如果我理解你的问题,这应该可以解决问题。 如果你使用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