/**
- 计算两个日期之间的天数
- 比如2016年4月10日到1991年2月2日是正确的,2016年4月10日到2134年5月15日
- 就差了两天 */ import java.util.Scanner;
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);//年月日相加获得天数
}
}