Problem

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.

Examples

Example 1

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

Example 2

1
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

Method 1 – Date Parsing and Day Counting

Intuition

Convert each date to the number of days since a fixed reference (e.g., 1971-01-01), then subtract. Leap years and month lengths must be handled.

Approach

  1. Parse year, month, day from each date string.
  2. For each date, count total days since 1971-01-01.
  3. Subtract the two counts and return the absolute value.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
class Solution {
public:
    int days(string date) {
        int y = stoi(date.substr(0,4)), m = stoi(date.substr(5,2)), d = stoi(date.substr(8,2));
        int days = d;
        static int mdays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
        for (int yy = 1971; yy < y; ++yy)
            days += 365 + ((yy%4==0 && yy%100!=0) || yy%400==0);
        for (int mm = 1; mm < m; ++mm) {
            if (mm == 2 && ((y%4==0 && y%100!=0) || y%400==0)) days += 29;
            else days += mdays[mm-1];
        }
        return days;
    }
    int daysBetweenDates(string date1, string date2) {
        return abs(days(date1)-days(date2));
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import "strconv"
func days(date string) int {
    y,_ := strconv.Atoi(date[:4])
    m,_ := strconv.Atoi(date[5:7])
    d,_ := strconv.Atoi(date[8:])
    days := d
    mdays := []int{31,28,31,30,31,30,31,31,30,31,30,31}
    for yy := 1971; yy < y; yy++ {
        days += 365
        if (yy%4==0 && yy%100!=0) || yy%400==0 { days++ }
    }
    for mm := 1; mm < m; mm++ {
        if mm == 2 && ((y%4==0 && y%100!=0) || y%400==0) { days += 29 } else { days += mdays[mm-1] }
    }
    return days
}
func daysBetweenDates(date1, date2 string) int {
    d1 := days(date1)
    d2 := days(date2)
    if d1 > d2 { return d1-d2 } else { return d2-d1 }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public int daysBetweenDates(String date1, String date2) {
        return Math.abs(days(date1)-days(date2));
    }
    int days(String date) {
        int y = Integer.parseInt(date.substring(0,4));
        int m = Integer.parseInt(date.substring(5,7));
        int d = Integer.parseInt(date.substring(8));
        int days = d;
        int[] mdays = {31,28,31,30,31,30,31,31,30,31,30,31};
        for (int yy = 1971; yy < y; ++yy)
            days += 365 + ((yy%4==0 && yy%100!=0) || yy%400==0 ? 1 : 0);
        for (int mm = 1; mm < m; ++mm)
            days += (mm==2 && ((y%4==0 && y%100!=0) || y%400==0)) ? 29 : mdays[mm-1];
        return days;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    fun daysBetweenDates(date1: String, date2: String): Int {
        fun days(date: String): Int {
            val y = date.substring(0,4).toInt()
            val m = date.substring(5,7).toInt()
            val d = date.substring(8).toInt()
            var days = d
            val mdays = arrayOf(31,28,31,30,31,30,31,31,30,31,30,31)
            for (yy in 1971 until y)
                days += 365 + if ((yy%4==0 && yy%100!=0) || yy%400==0) 1 else 0
            for (mm in 1 until m)
                days += if (mm==2 && ((y%4==0 && y%100!=0) || y%400==0)) 29 else mdays[mm-1]
            return days
        }
        return kotlin.math.abs(days(date1)-days(date2))
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        def days(date):
            y, m, d = map(int, [date[:4], date[5:7], date[8:]])
            mdays = [31,28,31,30,31,30,31,31,30,31,30,31]
            total = d
            for yy in range(1971, y):
                total += 365 + ((yy%4==0 and yy%100!=0) or yy%400==0)
            for mm in range(1, m):
                if mm == 2 and ((y%4==0 and y%100!=0) or y%400==0):
                    total += 29
                else:
                    total += mdays[mm-1]
            return total
        return abs(days(date1)-days(date2))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
impl Solution {
    pub fn days_between_dates(date1: String, date2: String) -> i32 {
        fn days(date: &str) -> i32 {
            let y = date[0..4].parse::<i32>().unwrap();
            let m = date[5..7].parse::<i32>().unwrap();
            let d = date[8..].parse::<i32>().unwrap();
            let mdays = [31,28,31,30,31,30,31,31,30,31,30,31];
            let mut total = d;
            for yy in 1971..y {
                total += 365 + if (yy%4==0 && yy%100!=0) || yy%400==0 { 1 } else { 0 };
            }
            for mm in 1..m {
                if mm == 2 && ((y%4==0 && y%100!=0) || y%400==0) {
                    total += 29;
                } else {
                    total += mdays[(mm-1) as usize];
                }
            }
            total
        }
        (days(&date1)-days(&date2)).abs()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function daysBetweenDates(date1: string, date2: string): number {
    function days(date: string): number {
        const y = parseInt(date.slice(0,4)), m = parseInt(date.slice(5,7)), d = parseInt(date.slice(8));
        const mdays = [31,28,31,30,31,30,31,31,30,31,30,31];
        let total = d;
        for (let yy = 1971; yy < y; ++yy)
            total += 365 + ((yy%4===0 && yy%100!==0) || yy%400===0 ? 1 : 0);
        for (let mm = 1; mm < m; ++mm)
            total += (mm===2 && ((y%4===0 && y%100!==0) || y%400===0)) ? 29 : mdays[mm-1];
        return total;
    }
    return Math.abs(days(date1)-days(date2));
}

Complexity

  • ⏰ Time complexity: O(Y) (Y = year difference)
  • 🧺 Space complexity: O(1)