# java 课后习题 计算两个日期之间的天数

1.绝对值 Math.abs() 的运用
2.str1.splist() 字符串分割方法的运用
3.字符串强转整形Integer.parseInt()的运用

public class Study {

//练习 计算两个日期之间含有多少天
public static void main(String[] args) {
System.out.println("请输入第一个日期 用\"-\"分隔 例:2019-06-02");
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();

System.out.println("请输入第二个日期 用\"-\"分隔 例:2019-06-02");
String str2 = scan.nextLine();

//put the Str to the Strsp
String[] strsp1 = str1.split("\\-");
String[] strsp2 = str2.split("\\-");

//实例化YearMonthDay

YearMonthDay ymd = new YearMonthDay(strsp1,strsp2);
System.out.println("两者相差："+Math.abs(ymd.allDayOne()-ymd.allDayTwo())+"天");

}
}

class YearMonthDay{

int year1;
int month1;
int day1;

int year2;
int month2;
int day2;

int allDayOne;
int allDayTwo;

public YearMonthDay(String[] strsp1,String[] strsp2){
//将分隔后的字符串分别 转换为int；
this.year1 = Integer.parseInt(strsp1[0]);
this.month1 = Integer.parseInt(strsp1[1]);
this.day1= Integer.parseInt(strsp1[2]);

this.year2 = Integer.parseInt(strsp2[0]);
this.month2 = Integer.parseInt(strsp2[1]);
this.day2 = Integer.parseInt(strsp2[2]);

}

public int allDayOne(){

//计算第一次输入的年总天数
for (int i = 1900;i<year1;i++){
//判断闰不闰
if ((year1 % 4 ==0 && year1 % 100 != 0) || year1 % 400 == 0){

allDayOne +=366;
}else{
allDayOne +=365;
}

}
//累加月份天数
for (int m = 1;m<month1;m++){

switch (m){
case 2: if ((year1 % 4 ==0 && year1 % 100 != 0) || year1 % 400 == 0){
allDayOne +=29;
}else {
allDayOne += 28;
}
break;

case 1: case 3: case 5: case 7: case 8: case 10: case 12:allDayOne += 31;break;

default:allDayOne +=30;break;

}
}

return allDayOne+day1;
}

public int allDayTwo(){

//计算第二次输入的年总天数
for (int i = 1900;i<year2;i++){
//判断闰不闰
if ((year2 % 4 ==0 && year2 % 100 != 0) || year2 % 400 == 0){

allDayTwo +=366;
}else{
allDayTwo +=365;
}
}

for (int m = 1;m<month2;m++){

switch (m){
case 2: if ((year2 % 4 ==0 && year2 % 100 != 0) || year2 % 400 == 0){
allDayTwo +=29;
}else {
allDayTwo += 28;
}
break;

case 1: case 3: case 5: case 7: case 8: case 10: case 12:allDayTwo += 31;break;

default:allDayTwo +=30;break;

}
}

return allDayTwo+day2;
}

@Override
public String toString() {
return "YearMonthDay{" +
"year1=" + year1 +
", month1=" + month1 +
", day1=" + day1 +
", year2=" + year2 +
", month2=" + month2 +
", day2=" + day2 +
'}';
}
}
11-12 20万+

11-23 1506
05-24 1万+
12-13 5348
02-08 135
11-23 9243
10-22 1万+