Skip to main content
Back to problems
#1360
Easy Algorithms

Number of days between two dates

Math String
52.4% acceptance
Feb 25, 2026
434
1321
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.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn days_between_dates(date1: String, date2: String) -> i32 {
    fn to_days(s: &str) -> i32 {
      let parts: Vec<i32> = s.split('-').map(|x| x.parse().unwrap()).collect();
      let (y, m, d) = (parts[0], parts[1], parts[2]);
      let mut days = 0i32;
      // days from year 1971
      for yr in 1971..y {
        days += if is_leap(yr) { 366 } else { 365 };
      }
      let mdays = [31, if is_leap(y) { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      for mo in 0..(m - 1) as usize {
        days += mdays[mo];
      }
      days += d;
      days
    }
    fn is_leap(y: i32) -> bool {
      (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
    }
    (to_days(&date1) - to_days(&date2)).abs()
  }
}