Write a program to count the number of days between two dates.

    The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

    Example 1:

    1. Input: date1 = "2019-06-29", date2 = "2019-06-30"
    2. Output: 1

    Example 2:

    1. Input: date1 = "2020-01-15", date2 = "2019-12-31"
    2. Output: 15

    Constraints:

    • The given dates are valid dates between the years 1971 and 2100.

    题意

    计算两个日期之间的天数。

    思路

    几种方法:

    1. 直接调用java API;
    2. 累加较小日期的天数,直到两日期相等;
    3. 将每个日期都转化为到1970-01-00的天数,最后相减(实际上就是自己实现了java API)

    代码实现 - API

    1. import java.time.LocalDate;
    2. class Solution {
    3. public int daysBetweenDates(String date1, String date2) {
    4. return (int) Math.abs(LocalDate.parse(date1).toEpochDay() - LocalDate.parse(date2).toEpochDay());
    5. }
    6. }

    代码实现 - 累加

    1. class Solution {
    2. public int daysBetweenDates(String date1, String date2) {
    3. if (date1.compareTo(date2) > 0) {
    4. String temp = date1;
    5. date1 = date2;
    6. date2 = temp;
    7. }
    8. String[] s1 = date1.split("-"), s2 = date2.split("-");
    9. int y1 = Integer.parseInt(s1[0]), y2 = Integer.parseInt(s2[0]);
    10. int m1 = Integer.parseInt(s1[1]), m2 = Integer.parseInt(s2[1]);
    11. int d1 = Integer.parseInt(s1[2]), d2 = Integer.parseInt(s2[2]);
    12. int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    13. int count = 0;
    14. days[2] = isLeapYear(y1) ? 29 : 28;
    15. while (y1 != y2 || m1 != m2 || d1 != d2) {
    16. count++;
    17. d1++;
    18. if (d1 == days[m1] + 1) {
    19. d1 = 1;
    20. m1++;
    21. }
    22. if (m1 == 13) {
    23. m1 = 1;
    24. y1++;
    25. days[2] = isLeapYear(y1) ? 29 : 28;
    26. }
    27. }
    28. return count;
    29. }
    30. private boolean isLeapYear(int year) {
    31. return year % 100 != 0 && year % 4 == 0 || year % 400 == 0;
    32. }
    33. }

    代码实现 - 总天数相减

    1. class Solution {
    2. public int daysBetweenDates(String date1, String date2) {
    3. return Math.abs(toDays(date1) - toDays(date2));
    4. }
    5. private int toDays(String date) {
    6. int count = 0;
    7. String[] s = date.split("-");
    8. int y = Integer.parseInt(s[0]), m = Integer.parseInt(s[1]), d = Integer.parseInt(s[2]);
    9. int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    10. days[2] += isLeapYear(y) ? 1 : 0;
    11. for (int i = 1970; i < y; i++) {
    12. count += isLeapYear(i) ? 366 : 365;
    13. }
    14. count += d;
    15. for (int i = 1; i < m; i++) {
    16. count += days[i];
    17. }
    18. return count;
    19. }
    20. private boolean isLeapYear(int year) {
    21. return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    22. }
    23. }