Blogs Hub

by AskGif | Oct 18, 2020 | Category :coding | Tags : algorithm data-structure easy leetcode maths

Number of Days Between Two Dates - Maths - Easy - LeetCode

Number of Days Between Two Dates - Maths - Easy - LeetCode

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.

public class Solution {
    public int DaysBetweenDates(string date1, string date2) {
        return Math.Abs(countSince1971(date1) - countSince1971(date2));
    }
    
    public int countSince1971(String date) {
        var monthDays = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        var data = date.Split('-');
        
        int year = int.Parse(data[0]);
        int month = int.Parse(data[1]);
        int day = int.Parse(data[2]);
        
        for (int i = 1971; i < year; i++) {
            day += isALeapYear(i) ? 366 : 365;
        }
        for (int i = 1; i < month; i++) {
            if (isALeapYear(year) && i == 2) {
                day += 1;
            } 
            day += monthDays[i];
        }
        return day;
    }

    public bool isALeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }
}

Time Complexity: O(n)

Space Complexity: O(1)