判断年月日是否合格,显示是当年的第几天
思路:先判断输入的年是闰年还是平年,封装求每个月的最大天数的函数(下个月的第0天就是当前月的最后一天),判断月日是否合格,最后利用switch中没有break的穿透对天数进行叠加。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>作业</title>
</head>
<body>
<h1>页面输入年月日,如果年月日合格就计算并显示是当年的第几天,如果不合格就显示日期不合格</h1>
<input type="text" id="oYear" placeholder="请输入正确的年">
<input type="text" id="oMonth" placeholder="请输入正确的月">
<input type="text" id="oDay" placeholder="请输入正确的日">
<button id="oButton">计算第几天</button>
<input type="text" id="oResult" placeholder="结果">
</body>
<script>
// 编写函数,完成日期的检验并计算天数
//是否为闰年
function isRun(year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
//每月的最大天数
function maxDay(year, month) {
var max_day = 31;
if (month == 4 || month == 6 || month == 9 || month == 11) {
max_day = 30;
}
if (month == 2) {
max_day = isRun(year) ? 29 : 28;
}
return max_day;
}
//判断年月日是否合格
function isQualified(year, month, day) {
var max_day = maxDay(year, month);
if (year % 1 == 0 && year > 0) {
if (month % 1 == 0 && month >= 1 && month <= 12) {
if (day % 1 == 0 && day >= 1 && day <= max_day) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
// console.log(isQualified(2020, 12, 2));
//计算天数
function caclDate(year, month, day) {
var sum = 0;
if (isQualified(year, month, day)) {
switch (month * 1) {
case 12: sum += 30;
case 11: sum += 31;
case 10: sum += 30;
case 9: sum += 31;
case 8: sum += 31;
case 7: sum += 30;
case 6: sum += 31;
case 5: sum += 30;
case 4: sum += 31;
case 3: sum += isRun(year) ? 29 : 28; //er
case 2: sum += 31;
case 1: sum += day;
}
return sum;
}
return false;
}
oButton.onclick = function () {
var day = oDay.value * 1;
var month = oMonth.value * 1;
var year = oYear.value * 1;
var res = caclDate(year, month, day);
oResult.value = res;
}
</script>
</html>