Java Calculate Number of Days Between Two Date

Tags: Java Date TimeUnit DateUtil

In this Java tutorial, we learn how to calculate the number of days between two Date objects in Java programming language.

How to calculate number of days between two Date objects in Java

At this first step, we create a new Java class named DateUtil, and implement a new static method named getNumberOfDaysBetween(Date start, Date end), in this method we follow these step to calculate number of days between two Date values.

  • Step 1: calculate number of milliseconds between two Date
  • Step 2: calculate number of days based on number of milliseconds using the TimeUnit.DAYS.convert(long sourceDuration, TimeUnit sourceUnit) method.

DateUtil.java

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DateUtil {

    /**
     * This method to get number of days between two Date objects.
     * @param start the start Date object
     * @param end the end Date object
     * @return the number of days between start and end Date.
     */
    public static long getNumberOfDaysBetween(Date start, Date end) {
        long numberOfMilliseconds = end.getTime() - start.getTime();
        long numberOfDays = TimeUnit.DAYS.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
        return numberOfDays;
    }

}

In the following example Java program, we learn how to use the above DateUtil class to calculate number of days between two Date objects in Java program.

NumberOfDaysBetweenDateExample.java

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class NumberOfDaysBetweenDateExample {
    public static void main(String... args) {
        Date startDate = new GregorianCalendar(2022, Calendar.JANUARY, 1).getTime();
        Date endDate = new GregorianCalendar(2022, Calendar.DECEMBER, 31).getTime();

        // Calculate Number of Days Between Two Date objects
        long numberOfDays = DateUtil.getNumberOfDaysBetween(startDate, endDate);

        System.out.println("Start Date: " + startDate);
        System.out.println("End Date: " + endDate);
        System.out.println("Number of days: " + numberOfDays);
    }
}
The output as below.
Start Date: Sat Jan 01 00:00:00 ICT 2022
End Date: Sat Dec 31 00:00:00 ICT 2022
Number of days: 364

Happy Coding 😊

Java Calculate Number of Hours Between Two Date

Java Calculate Number of Minutes Between Two Date

Java Calculate Number of Seconds Between Two Date

Java Calculate Number of Milliseconds Between Two Date

Java Calculate Number of Days Between Two Calendar

Java Calculate Number of Hours Between Two Calendar

Java Calculate Number of Minutes Between Two Calendar

Java Calculate Number of Seconds Between Two Calendar

Java Calculate Number of Milliseconds Between Two Calendar