Java Program to Calculate Time Difference In Hours
Chapter:
Date and Time
Last Updated:
20-09-2023 14:56:21 UTC
Program:
/* ............... START ............... */
import java.time.LocalDateTime;
import java.time.Duration;
public class TimeDifferenceCalculator {
public static void main(String[] args) {
// Create two LocalDateTime objects representing two points in time
LocalDateTime startTime = LocalDateTime.of(2023, 9, 20, 10, 0); // Replace with your start time
LocalDateTime endTime = LocalDateTime.of(2023, 9, 20, 15, 30); // Replace with your end time
// Calculate the time difference in hours
Duration duration = Duration.between(startTime, endTime);
long hours = duration.toHours();
// Display the result
System.out.println("Time difference in hours: " + hours);
}
}
/* ............... END ............... */
Output
Time difference in hours: 5
In this example, the program calculates the time difference between a start
time of "10:00 AM" and an end time of "3:30 PM," resulting in a time difference of 5 hours.
Notes:
-
In this example, you create two LocalDateTime objects, startTime and endTime, representing the two points in time for which you want to calculate the time difference. You then use Duration.between() to calculate the duration between these two times, and finally, you convert the duration to hours using toHours().