Java Calculate Number of Minutes Between Two Date

Tags: Java Date TimeUnit DateUtil

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

How to calculate number of minutes 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 getNumberOfMinutesBetween(Date start, Date end), in this new method we follow these step to calculate number of minutes between start and end Date values.

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

}

In the following example Java code, we learn how to use the above DateUtil method to calculate number of minutes between two Date values in Java program.

NumberOfMinutesBetweenDateExample.java

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

public class NumberOfMinutesBetweenDateExample {
    public static void main(String... args) {
        Date startDate = new GregorianCalendar(2022, Calendar.JULY, 1).getTime();
        Date endDate = new GregorianCalendar(2022, Calendar.JULY, 2).getTime();

        // Calculate Number of Minutes Between Two Date objects
        long numberOfMinutes = DateUtil.getNumberOfMinutesBetween(startDate, endDate);

        System.out.println("Start Date: " + startDate);
        System.out.println("End Date: " + endDate);
        System.out.println("Number of minutes: " + numberOfMinutes);
    }
}
The output as below.
Start Date: Fri Jul 01 00:00:00 ICT 2022
End Date: Sat Jul 02 00:00:00 ICT 2022
Number of minutes: 1440

Happy Coding 😊

Java Calculate Number of Days Between Two Date

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