/**
public class Test03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入兩個日期");
int year1 = scanner.nextInt();
int month1 = scanner.nextInt();
int day1 = scanner.nextInt();
int year2 = scanner.nextInt();
int month2 = scanner.nextInt();
int day2 = scanner.nextInt();
System.out.println("兩個日期相差"+ Math.abs(switch1(year1, month1, day1)
- switch1(year2, month2, day2)) + "天");
}
/**
* 該方法用於做閏年判斷
* 是閏年返回true,不是閏年則返回false
* return boolean;
* @param year
* @return
/
public static boolean isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return true;
}
return false;
}
/*
* 該方法用於獲取某年在某個月的天數
* @param year
* @param month
* @return
*/
public static int daysOfMonth(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
throw new RuntimeException("月份輸入有誤");
}
}
/**
* 該方法用來將一個日期轉化為距公元0年的天數;
* 負數為公元前的,正數為公元後;
* @param year
* @param month
* @param day
* @return
*/
public static int switch1(int year, int month, int day) {
int y = 0;//給定年份到公元0年的天數
int temp = 0;//中間變量,用來獲取當前年份的天數的;
/*
*
* 1.如果year=0,只需計算當前月到元月的天數(不含本月)m+day
* 2.若year>0,計算當前年份到公元0年的天數(不含本年)y+m+day
* 3.若year<0;此時y我負值y+m+day;
*/
while(!(year==0)){
if(year>0){
temp=isLeapYear(year-1)?366:365;
year--;
}else{
temp=-(isLeapYear(year)?366:365);
year++;
}
y+=temp;
}
int m = 0;//當前月在這一年中的已過的天數,不包含本月
for (; month > 1; month--) {
m += daysOfMonth(year, month - 1);
}
return (y + m + day);//年月日相加獲得天數
}
}
y=((isLeapYear(--year))?365*year+(year/4-year/100+year/400):0);是這麼寫嗎?