题目描述:输入一个日期,判断该日期是该年的第几天
package com.wyj.interview.realtopic;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* @description: 输入一个年月日,输出该日期是这一年的第几天
* @author wangyijun01_sx@qiyi.com
* @date 2018/12/29 14:19
*/
public class getDaysByDate {
private static final Integer bigMonth = 31;
private static final Integer smallMonth = 30;
private static Set<String> BIG_MONTHS = new HashSet<>();
private static Set<String> SMALL_MONTHS = new HashSet<>();
static {
BIG_MONTHS.add("01");
BIG_MONTHS.add("03");
BIG_MONTHS.add("05");
BIG_MONTHS.add("07");
BIG_MONTHS.add("08");
BIG_MONTHS.add("10");
BIG_MONTHS.add("12");
SMALL_MONTHS.add("04");
SMALL_MONTHS.add("06");
SMALL_MONTHS.add("09");
SMALL_MONTHS.add("11");
}
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入日期(格式:yyyy-MM-dd)");
String dateStr = sc.next();
System.out.println(getTotalDays(dateStr));
} catch (Exception e) {
System.out.println("格式输入错误,请重新输入");
e.printStackTrace();
}
}
private static Integer getTotalDays(String date) {
String[] strs = date.split("-");
String yearStr = strs[0];
Integer year = Integer.valueOf(yearStr);
String month = strs[1];
String day = strs[2];
Integer days = Integer.valueOf(day);
Integer totalDays = 0;
switch (month) {
case "12":
totalDays += bigMonth;
case "11":
totalDays += smallMonth;
case "10":
totalDays += bigMonth;
case "09":
totalDays += smallMonth;
case "08":
totalDays += bigMonth;
case "07":
totalDays += bigMonth;
case "06":
totalDays += smallMonth;
case "05":
totalDays += bigMonth;
case "04":
totalDays += smallMonth;
case "03":
totalDays += bigMonth;
case "02":
if ((year % 100 != 0 && year % 4 == 0) || (year % 100 == 0 && year % 400 == 0)) {
totalDays += 29;
}
else {
totalDays += 28;
}
case "01":
totalDays += bigMonth;
break;
}
Integer temp = 0;
if (BIG_MONTHS.contains(month)) {
temp = bigMonth;
} else if (SMALL_MONTHS.contains(month)) {
temp = smallMonth;
}else {
return days + bigMonth;
}
return totalDays + days - temp;
}
}