我想创建一个计数器来显示两个日期之间的差异。年、月、日和小时工作正常,但当实际分钟数为 0 时,分钟数将变为 -7。
起始日期为 2020/10/25/1/7 (y/m/d/h/M),其他日期为实际时间。
const beginning = new Date(2020, 9, 25, 1, 7);
window.addEventListener("load", function(event) {
window.setInterval(function() {
console.log(dateDiff(beginning, new Date()));
}, 1000)
});
function dateDiff(startingDate, endingDate) {
var startDate = new Date(new Date(startingDate).toISOString().substr(0, 10));
if (!endingDate) {
endingDate = new Date().toISOString().substr(0, 10);
}
var endDate = new Date(endingDate);
if (startDate > endDate) {
var swap = startDate;
startDate = endDate;
endDate = swap;
}
var startYear = startDate.getFullYear();
var february = (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 ? 29 : 28;
var daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var yearDiff = endDate.getFullYear() - startYear;
var monthDiff = endDate.getMonth() - startDate.getMonth();
if (monthDiff < 0) {
yearDiff--;
monthDiff += 12;
}
var dayDiff = endDate.getDate() - startDate.getDate();
if (dayDiff < 0) {
if (monthDiff > 0) {
monthDiff--;
} else {
yearDiff--;
monthDiff = 11;
}
dayDiff += daysInMonth[startDate.getMonth()];
}
var hourDiff = endingDate.getHours() - startingDate.getHours();
if (hourDiff < 0) {
if (dayDiff > 0) {
dayDiff--;
} else {
monthDiff--;
dayDiff += 1;
}
}
var minuteDiff = endingDate.getMinutes() - startingDate.getMinutes();
if (minuteDiff < 0) {
if (hourDiff > 0) {
hourDiff--;
} else {
dayDiff--;
hourDiff = 23;
}
}
return `${yearDiff} y, ${monthDiff} m, ${dayDiff} d, ${hourDiff} h, ${minuteDiff} m`;
}
抱歉回复晚了,这里是 html 代码:
<!-- COUNTER -->
<center>
<div>
<table class="Counterup" >
<tr style="font-size: 60px; ">
<td id="years">
<center>00</center>
</td>
<td id="months">
<center>00</center>
</td>
<td id="days">
<center>00</center>
</td>
<td id="hours">
<center>00</center>
</td>
<td id="minutes">
<center>00</center>
</td>
</tr>
<tr>
<td>
<center>     Jahre     </center>
</td>
<td>
<center>     Monate     </center>
</td>
<td>
<center>     Tage     </center>
</td>
<td>
<center>     Stunden     </center>
</td>
<td>
<center>     Minuten     </center>
</td>
</tr>
</table>
</div>
</center>