Java Calculate Number of Hours Between Two Date
Tags: Java Date TimeUnit DateUtil
In this Java tutorial, we learn how to calculate the number of hours between two Date objects in Java programming language.
How to calculate number of hours between two Date objects in Java
At this first step, we create a new Java class named DateUtil, and implement a static method named getNumberOfHoursBetween(Date start, Date end) which following these steps to return number of hours between start and end Date objects.
- Step 1: calculate the number of milliseconds between start and end Date values.
- Step 2: convert number of milliseconds into number of hours using the TimeUnit.HOURS.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 hours between two Date objects.
* @param start the start Date object
* @param end the end Date object
* @return the number of hours between start and end Date.
*/
public static long getNumberOfHoursBetween(Date start, Date end) {
long numberOfMilliseconds = end.getTime() - start.getTime();
long numberOfHours = TimeUnit.HOURS.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
return numberOfHours;
}
}
In the following example Java code, we learn how to use the above DateUtil method to calculate the number of hours between two Date values in Java program.
NumberOfHoursBetweenDateExample.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class NumberOfHoursBetweenDateExample {
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 Hours Between Two Date objects
long numberOfHours = DateUtil.getNumberOfHoursBetween(startDate, endDate);
System.out.println("Start Date: " + startDate);
System.out.println("End Date: " + endDate);
System.out.println("Number of hours: " + numberOfHours);
}
}
Start Date: Fri Jul 01 00:00:00 ICT 2022
End Date: Sat Jul 02 00:00:00 ICT 2022
Number of hours: 24
Happy Coding 😊
Related Articles
Java Calculate Number of Days 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
Java Calculate Number of Days Between Two Calendar
Java Calculate Number of Hours Between Two Calendar
Java Calculate Number of Minutes Between Two Calendar