Java Calculate Number of Hours Between Two Calendar
Tags: Java Calendar TimeUnit DateUtil
In this Java tutorial, we learn how to calculate number of hours between two Calendar objects in Java programming language.
How to calculate the number of hours between two Calendar objects in Java
At this first step, we create a new Java class named DateUtil, and implement a static method named, getNumberOfHoursBetween(Calendar start, Calendar end), this method follow these steps to calculate number of hours 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 hours using the TimeUnit.HOURS.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 hours between two Calendar objects.
* @param start the start Calendar object
* @param end the end Calendar object
* @return the number of hours between start and end Calendar.
*/
public static long getNumberOfHoursBetween(Calendar start, Calendar end) {
long numberOfMilliseconds = end.getTimeInMillis() - start.getTimeInMillis();
long numberOfHours = TimeUnit.HOURS.convert(numberOfMilliseconds, TimeUnit.MILLISECONDS);
return numberOfHours;
}
}
In the following example Java code, we learn how to use the above DateUtil class to calculate number of hours between two Calendar objects in Java program.
NumberOfHoursBetweenCalendarExample.java
import java.util.Calendar;
import java.util.GregorianCalendar;
public class NumberOfHoursBetweenCalendarExample {
public static void main(String... args) {
Calendar start = new GregorianCalendar(2022, Calendar.JULY, 1);
Calendar end = new GregorianCalendar(2022, Calendar.JULY, 2);
// Calculate Number of Hours Between Two Calendar objects
long numberOfHours = DateUtil.getNumberOfHoursBetween(start, end);
System.out.println("Start Date: " + start.getTime());
System.out.println("End Date: " + end.getTime());
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 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
Java Calculate Number of Days Between Two Date
Java Calculate Number of Hours Between Two Date
Java Calculate Number of Minutes Between Two Date