Coding
Algorithms

Days Between Dates

Difficulty

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Available in Python and C++. You are solving it in C++. Switch to Python

Implement days_between(start, end) where both arguments are "YYYY-MM-DD" strings, returning the signed number of days from start to end (positive when end is later, negative when earlier, zero when equal). Compute it yourself from the Gregorian calendar rules.

Settlement systems depend on date arithmetic: T+1 delivery, coupon accrual and day-count fractions.

long long days_between(const std::string& start, const std::string& end);

Do the calendar math yourself, without the <chrono> calendar types or any other calendar library. The exercise is the day-count algebra, and the <chrono> calendar would trivialise it. The editorial's follow-ups assume you did it by hand.

Gregorian leap rule: a year is a leap year if it is divisible by 4, except century years, which are leap only when divisible by 400. So 2000 and 2400 are leap years; 1900 is not.

Examples

days_between("2024-02-28", "2024-03-01");
// 2  (2024 is a leap year: Feb 29 sits in between)

days_between("2024-01-01", "2025-01-01");
// 366  (a leap year is 366 days long)

days_between("2026-03-01", "2026-02-01");
// -28  (signed: end before start goes negative)

Constraints

  • Years range from 1583 to 9999 (safely inside the Gregorian calendar); inputs are always valid dates in YYYY-MM-DD form.
  • The answer is exact integer arithmetic; there is nothing to round and no performance bar. The hidden tests are calendar edge cases: century non-leap years, the 400-year exceptions, and multi-millennium spans, so a hand-rolled month-by-month loop must get every rule right.
Rate this problem
Language:
Python 3.12C++23
days_between
Rate this problem