How to Calculate the Number of Days Between Two Dates?

In this post, we will tackle interesting coding interview question: determine the number of days between two given dates.

It might look straightforward at first, but it requires understanding the subtleties of our calendar system.

Problem Statement

Given two dates in the format YYYY-MM-DD, find out the number of days between them, without using any built-in date functions.

Solution Approach

At a high level, the approach can be broken down into three main steps:

  1. Convert each date into a number that represents the days elapsed since a fixed reference date.
  2. Compute the difference between these two numbers.
  3. Return the absolute value of this difference.

Handling Leap Years

As you know, every 4th year is a leap year, adding an extra day (February 29th) to our calendar. But there’s a caveat: years divisible by 100 aren’t leap years unless they’re also divisible by 400 (This exception keeps our calendar synchronized with Earth’s orbit around the Sun).

Calculating Days Since a Reference Point

The core idea behind our solution lies in this step. If we can compute the total number of days for each date since a reference point (let’s say 1971-01-01), the difference between these totals gives us our answer.

So the steps to calculate the number of days would be:

  1. Calculate days from the reference year (1971) up to the year before our date.
  2. Add days for each month of the date’s year leading up to the given month.
  3. Add days of the current month from the date.

Java Code

Here is the complete Java code to solve this problem:

public class DateDifferenceCalculator {

    /**
     * Check if a given year is a leap year.
     * @param year The year to be checked.
     * @return true if it's a leap year, false otherwise.
     */
    private boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

    /**
     * Calculate the number of days since 0001-01-01 for a given date.
     * @param date The date in format "YYYY-MM-DD".
     * @return The number of days since 0001-01-01.
     */
    private int daysSince1971(String date) {
        int[] months = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        String[] parts = date.split("-");
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int day = Integer.parseInt(parts[2]);

        for (int i = 1971; i < year; i++) {
            day += isLeapYear(i) ? 366 : 365;
        }

        for (int i = 1; i < month; i++) {
            if (i == 2 && isLeapYear(year)) {
                day += 1;
            }
            day += months[i];
        }

        return day;
    }

    /**
     * Calculate the number of days between two dates.
     * @param date1 The first date in format "YYYY-MM-DD".
     * @param date2 The second date in format "YYYY-MM-DD".
     * @return The absolute number of days between the two dates.
     */
    public int daysBetweenDates(String date1, String date2) {
        return Math.abs(daysSince1971(date1) - daysSince1971(date2));
    }

    public static void main(String[] args) {
        DateDifferenceCalculator calculator = new DateDifferenceCalculator();
        String date1 = "2021-03-12";
        String date2 = "2018-11-21";
        System.out.println("Days difference: " + calculator.daysBetweenDates(date1, date2));
    }
}

If you find this guide helpful, please share with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *