[Case] Judging a certain day is the day of the year

1. Analysis

1. First of all, you must know whether the year is a leap year or an ordinary year

2. Secondly, judge whether the month entered by the user is January, if it is, return the number of days directly; if not, first calculate the total number of days in the previous months (here, set February as 28 days), and then add the day how many days in the month

3. If the month entered by the user is greater than 2 and the year is a leap year, one more day should be added

2. Source code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>输入年月日判断该天是一年中的第几天</title>
	</head>
	<body>
		<script type="text/javascript">			
			//需要判断这个年份是不是闰年
			function isLeapYear(year){
				return year%4==0&&year%100!=0||year%400==0;
			};
			
			function getDays(year, month,day) {
				//定义变量存储对应的天数
				var days = day;
				//如果用户输入的是一月份,没必要向后算天数,直接返回天数
				if (month == 1) {
					 return days;
				};
				//代码执行到这里说明用户输入的不是1月份
				//定义一个数组,存储每个月份的天数
				var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
				//小于的是输入的月份-1
				for (var i = 0; i < month - 1; i++) {
					days += months[i];
				};
				//需要判断这个年份是不是闰年 如果是闰年并且输入月份大于2就加一天
				if(isLeapYear(year) && month>2){
					days++;
				};
				return days;
			};

			console.log(getDays(2020,3,5));//结果为65

		</script>
	</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/118424235