Skip to content

1360. Number of Days Between Two Dates

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:

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

Example 2:

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

Constraints:

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

Solution:

class Solution {
    public int daysBetweenDates(String date1, String date2) {
        return Math.abs(daysFromStart(date1) - daysFromStart(date2));
    }

    private int daysFromStart(String date){
        String[] parts = date.split("-");

        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int day = Integer.parseInt(parts[2]);

        int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        int days = 0;

        for (int y = 1971; y < year; y++){
            days += isLeap(y) ? 366 : 365;
        }

        for (int m = 1; m < month; m++){
            if (m == 2 && isLeap(year)){
                days = days + 29;
            }else{
                days = days + daysInMonth[m - 1];
            }
        }

        days = days + day;

        return days;
    }

    private boolean isLeap(int year){
        return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
    }
}