例:用for循环算出2017年9月8日至2020年8月27日一共有多少天
<script>
let year = 2017
let month = 9
let date = 8
let endYear = 2020
let endMonth = 8
let endDate = 27
let total = 0
total += date
//常用于确定次数的循环操作
for (let i = 1; i <= month - 1; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
total += 31
break;
case 1:
case 4:
case 6:
case 9:
case 11:
total += 30
break;
case 2:
total += 28
}
}
total = 365 - total //17年剩余的天数
//2020-8-27
for (let i = 1; i <= endMonth - 1; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
total += 31
break;
case 1:
case 4:
case 6:
case 9:
case 11:
total += 30
break;
case 2:
total += 29
}
}
total += (endYear - year - 1) * 365
console.log(total);