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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| class Solution { static int YEAR = 1969; static int MONTH = 1; static int DAY = 1; int[] DaysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
boolean isLeapYear(int year) { boolean flag = false; flag = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; if(flag) { DaysInMonth[2] = 29; } else { DaysInMonth[2] = 28; } return flag; }
boolean checkValid(int year, int month, int day) { isLeapYear(year); if (month > 12 || month < 0) { return false; } else return day >= 0 && day <= DaysInMonth[month]; }
int DateToNums(int year, int month, int day) { int num = 0; if (!checkValid(year, month, day)) { System.out.println("输入有误"); return 0; } if (year >= YEAR) { while (year >= YEAR) { day--; num++; if (day <= 0) { month--; if (month <= 0) { year--; isLeapYear(year); month = 12; day = 31; } else { day = DaysInMonth[month]; } } } return num - 1; } else { while (year < YEAR) { day++; num--; if (day > DaysInMonth[month]) { day = 1; month++; if (month > 12) { month = 1; year++; isLeapYear(year); } } } return num; } }
String NumsToDate(int num) { int year = YEAR; int month = MONTH; int day = DAY; boolean isLeapYear = false; if (num >= 0) { while (num > 0) { day++; if (day > DaysInMonth[month]) { day = 1; month++; } if (month > 12) { year++; month = 1; isLeapYear(year); } num--; } } else { while (num < 0) { day--; num++; if (day <= 0) { month--; day = DaysInMonth[month]; if (month <= 0) { month = 12; day = DaysInMonth[month]; year--; isLeapYear(year); } } } } return year + "年" + month + "月" + day + "日"; }
public static void main(String[] args) { Solution test = new Solution();
System.out.println(test.DateToNums(1972,1,1)); for (int i = -740; i < 1100; i++) { System.out.print(i+" "); System.out.println(test.NumsToDate(i)); } } }
|