Compare dates by calendar month
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's coding round, last asked Jun 2026. It tests dates, edge cases and requirements.
Define what it means for two dates to be within one calendar month of each other, exactly one month apart, or more than a month apart, and implement the comparison. "One month after" a date means the same day of the next month; when the next month has no such day (January 31), it means the last day of that month (February 28 or 29).
Interface
Unless you agree on a different interface with the interviewer, assume:
-
compare_month(a: date, b: date) -> str— returns"within","exactly"or"over". The order of the arguments does not matter: the earlier date is the start.
Example
compare_month(2024-01-15, 2024-02-14) -> "within"
compare_month(2024-01-15, 2024-02-15) -> "exactly"
compare_month(2024-01-31, 2024-02-29) -> "exactly" # leap year, clamped to Feb 29
compare_month(2023-01-31, 2023-02-28) -> "exactly" # clamped to Feb 28
compare_month(2024-03-01, 2024-01-31) -> "over" # start is Jan 31, a month later is Feb 29
compare_month(2024-12-20, 2025-01-21) -> "over" # crosses the year
Constraints
- Dates only, no times or time zones.
- Use the language's date library for leap years and month lengths; do not count days with 30 as a month.
Clarifying questions
- Does the order of the two dates matter?
- What is one month after January 31: February 28 (clamp) or March 3 (overflow)?
- Is the same day a month later "within" or "exactly"?
- Do times of day or time zones ever enter?
What a strong answer covers
- A written definition before code, with the clamping rule and the boundary stated.
- Implementation: order the dates, compute one month after the start by moving to the next month and clamping the day to that month's length, then compare.
- Why "30 days" or "difference in month numbers" is wrong, with a counterexample.
- Edge cases: month end, leap years, December to January, identical dates.
- Table-driven tests covering each case above.
Follow-ups
- Generalize to "within N months".
- The comparison must be symmetric. Is it? Find a pair where swapping the start date changes the answer under a different rule.
- Add times and time zones: what does "a month" mean for 23:30 on January 31 in one zone?
Where it's asked
- Apple · Coding · Last asked Jun 2026
What it tests
dates · edge cases · requirements
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
