1360. 日期之间隔几天『简单』

题目来源于力扣(LeetCode

一、题目

1360. 日期之间隔几天

提示:

给定的日期是 1971 年到 2100 年之间的有效日期。

二、解题思路

2.1 日期转数字计算差方式

  1. 分别计算两个日期距离 1971 年 1 月 1 日的天数

  2. 对得到的两个结果进行相减运算

三、代码实现

3.1 日期转数字计算差方式

// 分别计算两个日期与1971年1月1日之前的天数,再相减即得到日期之差
public static int daysBetweenDates(String date1, String date2) {
    int result = dateToDays(date1) - dateToDays(date2);
    return result > 0 ? result : -result;
}

// 计算该日期字符串与1971年1月1日之间的天数
public static int dateToDays(String date) {
    String[] strs = date.split("-");
    int year = Integer.valueOf(strs[0]);
    int month = Integer.valueOf(strs[1]);
    int day = Integer.valueOf(strs[2]);
    // 加上天数
    int days = day;
    // 12 月份的天数(平年的情况下)
    int[] dayOfMonthArr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    // 计算年份
    for (int i = 1971; i < year; i++) {
        if (isLeapYear(i)) {
            days += 366;
        } else {
            days += 365;
        }
        // days += isLeapYear(i) ? 366 : 365;
    }
    // 计算月份
    for (int j = 1; j < month; j++) {
        days += dayOfMonthArr[j - 1];
        // 闰年时,2月份多一天
        if (j == 2 && isLeapYear(year)) {
            days += 1;
        }
    }
    return days;
}

// 判断参数 year 年份是否闰年
public static boolean isLeapYear(int year) {
    // 能被 4 整除,且不被 100 整除的年份
    if (year % 4 == 0 && year % 100 != 0) {
        return true;
    }
    // 能被 400 整除的年份
    if (year % 400 == 0) {
        return true;
    }
    return false;
}

四、执行用时

4.1 日期转数字计算差方式

五、部分测试用例

public static void main(String[] args) {
//    String date1 = "2019-06-29", date2 = "2019-06-30";  // output:1
    String date1 = "2020-01-15", date2 = "2019-12-31";  // output:15

    int result = daysBetweenDates(date1, date2);
    System.out.println(result);
}
posted @ 2020-05-12 21:03  知音12138  阅读(180)  评论(0编辑  收藏  举报