Java Calculate Number of Milliseconds Between Two Date
In this Java tutorial, we learn how to calculate number of milliseconds between two Date objects in Java programming language.
How to calculate number of milliseconds between two Date objects in Java
In this first step, we create a new Java class named DateUtil, and implement a new method named getNumberOfMillisecondsBetween(Date start, Date end) to calculate number of milliseconds from given start and end Date objects as the following Java code.
DateUtil.java
import java.util.Date;
public class DateUtil {
/**
* This method to get number of milliseconds between two Date objects.
* @param start the start Date object
* @param end the end Date object
* @return the number of milliseconds between start and end Date.
*/
public static long getNumberOfMillisecondsBetween(Date start, Date end) {
long numberOfMilliseconds = end.getTime() - start.getTime();
return numberOfMilliseconds;
}
}
In the following example Java code, we learn how to use the above getNumberOfMillisecondsBetween(Date start, Date end) method to calculate the number of milliseconds between two Date objects in Java program.
NumberOfMillisecondsBetweenDateExample.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class NumberOfMillisecondsBetweenDateExample {
public static void main(String... args) {
Date startDate = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 30, 0).getTime();
Date endDate = new GregorianCalendar(2022, Calendar.JULY, 1, 8, 31, 0).getTime();
// Calculate Number of Milliseconds Between Two Date objects
long numberOfMilliseconds = DateUtil.getNumberOfMillisecondsBetween(startDate, endDate);
System.out.println("Start Date: " + startDate);
System.out.println("End Date: " + endDate);
System.out.println("Number of milliseconds: " + numberOfMilliseconds);
}
}
Start Date: Fri Jul 01 08:30:00 ICT 2022
End Date: Fri Jul 01 08:31:00 ICT 2022
Number of milliseconds: 60000
Happy Coding 😊
Related Articles
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 Days Between Two Calendar
Java Calculate Number of Hours Between Two Calendar
Java Calculate Number of Minutes Between Two Calendar