日期之间隔几天

请你编写一个程序来计算两个日期之间隔了多少天。

日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。

示例 1:

输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:

输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15

算出两个天数的差值

class Solution {
    public int daysBetweenDates(String date1, String date2) {
        //获取日期的年月日
        int year1 = Integer.parseInt(date1.substring(0,4));
        int momth1 = Integer.parseInt(date1.substring(5,7));
        int day1 = Integer.parseInt(date1.substring(8,10));
        int year2 = Integer.parseInt(date2.substring(0,4));
        int momth2 = Integer.parseInt(date2.substring(5,7));
        int day2 = Integer.parseInt(date2.substring(8,10));
        //分别计算两个date距离1971-1-1的天数,结果相差就是了
        momth1 = monthDays(momth1,year1);
        momth2 = monthDays(momth2,year2);
        year1 = yearDays(year1);
        year2 = yearDays(year2);
        day1 += year1 + momth1;
        day2 += year2 + momth2;
        return day1>day2?day1-day2:day2-day1;
    }

    private static int monthDays(int momth,int year) {
        int day = 0;
        int amount[] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        for(int i=1;i<momth;i++){
            if(i==2&&isLeapYear(year)){
                day+=29;
                continue;
            }
            day+= amount[i];
        }
        return day;
    }

    public static int yearDays(int year){
        int day = 0;
        for(int i = 1971;i<year;i++){
            day += isLeapYear(i)?366:365;
        }
        return day;
    }

    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

}
posted @ 2023-08-09 19:04  网抑云黑胶SVIP用户  阅读(7)  评论(0编辑  收藏  举报