Java Calculate Number of Days Between Two Calendar

Tags: Java Calendar TimeUnit DateUtil

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

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

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

  • Step 1: calculate number of milliseconds between start and end Calendar objects.
  • Step 2: convert number of milliseconds into number of days using the TimeUnit.DAYS.convert(long sourceDuration, TimeUnit sourceUnit) method.

DateUtil.java

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class DateUtil {

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

}

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

NumberOfDaysBetweenCalendarExample.java

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

public class NumberOfDaysBetweenCalendarExample {
    public static void main(String... args) {
        Calendar start = new GregorianCalendar(2022, Calendar.JULY, 1);
        Calendar end = new GregorianCalendar(2022, Calendar.AUGUST, 1);

        // Calculate Number of Days Between Two Calendar objects
        long numberOfDays = DateUtil.getNumberOfDaysBetween(start, end);

        System.out.println("Start Date: " + start.getTime());
        System.out.println("End Date: " + end.getTime());
        System.out.println("Number of days: " + numberOfDays);
    }
}
The output as below.
Start Date: Fri Jul 01 00:00:00 ICT 2022
End Date: Mon Aug 01 00:00:00 ICT 2022
Number of days: 31

Happy Coding 😊

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

Java Calculate Number of Days Between Two Date

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