求给定的日期是当年中的第几天

1.步骤

输出年月日,计算天数,输出是第几天

2.思路

①判断所给年份是否为闰年

②定义一个计算天数的函数

③输出年月日

④通过调用函数得出结果

3.对应代码

//判断是否为闰年
			function isLeapYear(year) {
				if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
					return true;
				} else {
					return false;
				}
			}

//定义一个求天数的函数
			function getDaysByDate(year, month, day) {
				//定义一个总天数
				var days = 0
				switch (month) {
					case 12:
						//11月的天数
						days += 30
					case 11:
						//10月的天数
						days += 31
					case 10:
						//9月的天数
						days += 30
					case 9:
						//8月的天数
						days += 31
					case 8:
						//7月的天数
						days += 31
					case 7:
						//6月的天数
						days += 30
					case 6:
						//5月的天数
						days += 31
					case 5:
						//4月的天数
						days += 30
					case 4:
						//3月的天数
						days += 31
					case 3:
						//2月的天数
						days += isLeapYear(year) ? 29 : 28
					case 2:
						//1月的天数
						days += 31
					case 1:
						//当前月天数
						days += day
						break
					default:
						break;
				}
				return days
			}

//输出年月日
			var year = parseInt(prompt("请输入年份:"))
			var month = parseInt(prompt("请输入月份:"))
			var day = parseInt(prompt("请输入天数:"))

var result = getDaysByDate(year,month,day);
			document.write(year+"年"+month+"月"+day+"日是本年的第"+result+"天")

4.思路整理 总结

如何判断是否为闰年:通过if..else..判断出是否为闰年

怎么写定义计算天数的代码:通过switch来写,判断月份然后一次往下累加,把上面的break去掉,留下一月份的break

5.全部代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//判断是否为闰年
			function isLeapYear(year) {
				if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
					return true;
				} else {
					return false;
				}
			}
			//定义一个求天数的函数
			function getDaysByDate(year, month, day) {
				//定义一个总天数
				var days = 0
				switch (month) {
					case 12:
						//11月的天数
						days += 30
					case 11:
						//10月的天数
						days += 31
					case 10:
						//9月的天数
						days += 30
					case 9:
						//8月的天数
						days += 31
					case 8:
						//7月的天数
						days += 31
					case 7:
						//6月的天数
						days += 30
					case 6:
						//5月的天数
						days += 31
					case 5:
						//4月的天数
						days += 30
					case 4:
						//3月的天数
						days += 31
					case 3:
						//2月的天数
						days += isLeapYear(year) ? 29 : 28
					case 2:
						//1月的天数
						days += 31
					case 1:
						//当前月天数
						days += day
						break
					default:
						break;
				}
				return days
			}
			//输出年月日
			var year = parseInt(prompt("请输入年份:"))
			var month = parseInt(prompt("请输入月份:"))
			var day = parseInt(prompt("请输入天数:"))
			var result = getDaysByDate(year,month,day);
			document.write(year+"年"+month+"月"+day+"日是本年的第"+result+"天")
		</script>
	</head>
	<body>
	</body>
</html>

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值