Java Calculate Number of Minutes Between Two Calendar

Tags: Java Calendar TimeUnit DateUtil

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

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

Firstly, we create a new Java class named DateUtil, and implement a new static method named getNumberOfMinutesBetween(Calendar start, Calendar end), this method follow following steps to calculate number of minutes between two Calendar objects.

  • Step 1: calculate the number of milliseconds between two given Calendar objects.
  • Step 2: convert number of milliseconds into number of minutes using the TimeUnit.MINUTES.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 minutes between two Calendar objects.
     * @param start the start Calendar object
     * @param end the end Calendar object
     * @return the number of minutes between start and end Calendar.
     */
    public static long getNumberOfMinutesBetween(Calendar start, Calendar end) {
        long numberOfMilliseconds = end.getTimeInMillis() - start.getTimeInMillis();
        long numberOfMinutes = TimeUnit.MINUTES.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
        return numberOfMinutes;
    }

}

In the following example Java code, we learn how to use the above DateUtil class to calculate number of minutes with given start and end Calendar objects in Java program.

NumberOfMinutesBetweenCalendarExample.java

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

public class NumberOfMinutesBetweenCalendarExample {
    public static void main(String... args) {
        Calendar start = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 10, 0);
        Calendar end = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 30, 0);

        // Calculate Number of Minutes Between Two Calendar objects
        long numberOfMinutes = DateUtil.getNumberOfMinutesBetween(start, end);

        System.out.println("Start Date: " + start.getTime());
        System.out.println("End Date: " + end.getTime());
        System.out.println("Number of minutes: " + numberOfMinutes);
    }
}
The output as below.
Start Date: Fri Jul 01 08:10:00 ICT 2022
End Date: Fri Jul 01 08:30:00 ICT 2022
Number of minutes: 20

Happy Coding 😊

Java Calculate Number of Days Between Two Calendar

Java Calculate Number of Hours 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