判断某一天是今年的第几天

本文最后更新于:2021年9月20日 上午

如题。。。

判断某一天是今年的第几天

解题思路

  1. 先计算出当月月份之前的天数,因为根据年份和月份都可以确定每一个具体的天数
  2. 把上一步计算出来值和天数相加即是答案

模块划分

  1. 获取某一个月份的天数的模块
  2. 是否是论年的模块
  3. 获取某一个月份之前月份的累积天数

函数实现

  1. 是否是论年的模块
1
2
3
4
// isLeapYear 判断是否是润年
public static boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
  1. 获取某一个月份的天数的模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// getMonthDay 获取某一个月份的天数
public static int getMonthDay(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
return 28 + (isLeapYear(year) ? 1 : 0);
default:
return 30;
}
}
  1. 获取某一个月份之前月份的累积天数
1
2
3
4
5
6
7
8
// getTotalDaySinceMonth 获取某一个月份之前月份的累积天数
public static int getTotalDaySinceMonth(int year, int month) {
int totalDay = 0;
for (int i = 1; i < month; i++) {
totalDay += getMonthDay(year, month);
}
return totalDay;
}

最后程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package basic;

import java.util.Scanner;

public class Main {
// isLeapYear 判断是否是润年
public static boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}

// getMonthDay 获取某一个月份的天数
public static int getMonthDay(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
return 28 + (isLeapYear(year) ? 1 : 0);
default:
return 30;
}
}

// getTotalDaySinceMonth 获取某一个月份之前月份的累积天数
public static int getTotalDaySinceMonth(int year, int month) {
int totalDay = 0;
for (int i = 1; i < month; i++) {
totalDay += getMonthDay(year, i);
}
return totalDay;
}

//
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("请输入年月日(格式2020-01-02):");
String str = in.next();
String[] split = str.split("-");
int year = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int day = Integer.parseInt(split[2]);
int totalDay = getTotalDaySinceMonth(year, month);
System.out.println("总天数为:" + (totalDay + day));
}
}