请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD
,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30" 输出:1
import java.time.LocalDate;
class Solution {
public int daysBetweenDates(String date1, String date2) {
String[] s1=date1.split("-");
String[] s2=date2.split("-");
LocalDate localDate1=LocalDate.of(Integer.parseInt(s1[0]), Integer.parseInt(s1[1]),Integer.parseInt(s1[2]));
LocalDate localDate2=LocalDate.of(Integer.parseInt(s2[0]), Integer.parseInt(s2[1]),Integer.parseInt(s2[2]));
if(s1[0].equals(s2[0])) return Math.abs(localDate1.getDayOfYear()-localDate2.getDayOfYear());
int year1=0;
int month1=0;
int day1=0;
int year2=0;
int month2=0;
int day2=0;
if(Integer.parseInt(s1[0])>Integer.parseInt(s2[0])) {
year1=Integer.parseInt(s2[0]);
month1=Integer.parseInt(s2[1]);
day1=Integer.parseInt(s2[2]);
year2=Integer.parseInt(s1[0]);
month2=Integer.parseInt(s1[1]);
day2=Integer.parseInt(s1[2]);
}
else {
year1=Integer.parseInt(s1[0]);
month1=Integer.parseInt(s1[1]);
day1=Integer.parseInt(s1[2]);
year2=Integer.parseInt(s2[0]);
month2=Integer.parseInt(s2[1]);
day2=Integer.parseInt(s2[2]);
}
int num=0;
for (int i = year1+1; i < year2; i++) {
if(i%400==0||(i%100!=0&&i%4==0)) {
num+=366;
}
else num+=365;
}
LocalDate localDate3=LocalDate.of(year1, month1, day1);
LocalDate localDate4=LocalDate.of(year2, month2, day2);
num+=localDate4.getDayOfYear()+365-localDate3.getDayOfYear();
if(year1%400==0||(year1%100!=0&&year1%4==0)) num+=1;
return num;
}
}