Java Calculate Number of Milliseconds Between Two Calendar

Tags: Java Calendar DateUtil

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

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

In this first step, we create a new Java class named DateUtil, and implement the static method named getNumberOfMillisecondsBetween(Calendar start, Calendar end) to return number of milliseconds between start and end Calendar values as the following Java code.

DateUtil.java

import java.util.Calendar;

public class DateUtil {

    /**
     * This method to get number of milliseconds between two Calendar objects.
     * @param start the start Calendar object
     * @param end the end Calendar object
     * @return the number of milliseconds between start and end Calendar.
     */
    public static long getNumberOfMillisecondsBetween(Calendar start, Calendar end) {
        long numberOfMilliseconds = end.getTimeInMillis() - start.getTimeInMillis();
        return numberOfMilliseconds;
    }

}

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

NumberOfMillisecondsBetweenCalendarExample.java

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

public class NumberOfMillisecondsBetweenCalendarExample {
    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, 11, 0);

        // Calculate Number of Milliseconds Between Two Calendar objects
        long numberOfMilliseconds = DateUtil.getNumberOfMillisecondsBetween(start, end);

        System.out.println("Start Date: " + start.getTime());
        System.out.println("End Date: " + end.getTime());
        System.out.println("Number of milliseconds: " + numberOfMilliseconds);
    }
}
The output as below.
Start Date: Fri Jul 01 08:10:00 ICT 2022
End Date: Fri Jul 01 08:11:00 ICT 2022
Number of milliseconds: 60000

Happy Coding 😊

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 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