首先,要意识到new Date(2024,12,1)
与new Date(2025,0,1)
相同,因为月份参数是从零开始的.
其次,我不会在您的百分比公式中使用round
,因为这意味着您将在目标日期前两天达到round
%.改用floor
.
您可以取百分比,加一,然后颠倒公式,以知道何时百分比将增加一个单位.
这是一个片段:
const start = new Date(2024,0,1);
const end = new Date(2025,0,1);
const outTime = document.querySelector("#datetime");
const outPct = document.querySelector("#percentage");
const outRem = document.querySelector("#remaining");
setInterval(function () {
const today = new Date();
outTime.textContent = today.toLocaleString("bg").replace(/ \D+/g, " ");
if (today >= end) {
outPct.textContent = "100%";
outRem.textContent = "";
return;
}
const total = end - start;
const progress = today - start;
const pct = Math.floor(progress / total * 100);
outPct.textContent = pct + "%";
const next = (pct+1) / 100 * total;
const countdown = Math.ceil((next - progress) / 1000);
const hours = Math.floor(countdown / 3600);
const minutes = Math.floor((countdown % 3600) / 60);
const seconds = countdown % 60;
outRem.textContent = `${hours} hours, ${minutes} minutes and ${seconds} seconds`
.replace(/\b(1 \w+)s\b/g, "$1");
}, 1);
Current time: <span id="datetime"></span><br>
Progress: <span id="percentage"></span><br>
Until next %-increment: <span id="remaining"></span><br>
像这样很难测试正确性,因为百分比增加需要很长时间,因此可以使用两个彼此接近的日期来做到这一点,例如仅相隔1小时(当前小时的开始和结束):
const start = new Date();
start.setMinutes(0, 0, 0); // Start of the current hour
const end = new Date();
end.setMinutes(60, 0, 0); // End of the current hour
const outTime = document.querySelector("#datetime");
const outPct = document.querySelector("#percentage");
const outRem = document.querySelector("#remaining");
setInterval(function () {
const today = new Date();
outTime.textContent = today.toLocaleString("bg").replace(/ \D+/g, " ");
if (today >= end) {
outPct.textContent = "100%";
outRem.textContent = "";
return;
}
const total = end - start;
const progress = today - start;
const pct = Math.floor(progress / total * 100);
outPct.textContent = pct + "%";
const next = (pct+1) / 100 * total;
const countdown = Math.ceil((next - progress) / 1000);
const hours = Math.floor(countdown / 3600);
const minutes = Math.floor((countdown % 3600) / 60);
const seconds = countdown % 60;
outRem.textContent = `${hours} hours, ${minutes} minutes and ${seconds} seconds`
.replace(/\b(1 \w+)s\b/g, "$1");
}, 1);
Current time: <span id="datetime"></span><br>
Progress: <span id="percentage"></span><br>
Until next %-increment: <span id="remaining"></span><br>