Java Program to Calculate Difference Between Two Time Periods

In this java program, we will learn about how to calculate the difference between two time periods.

Given two time instants in HH:mm:ss format, we have to print the difference between these two time periods in hours, minutes and seconds as follows:

Time1: 02:10:00
Time2: 04:20:00
Difference : 2 hours, 10 minutes, 0 seconds
Here is the algorithm to calculate the difference between two time periods.
  • Create an object of SimpleDateFormat class by using the string format "HH:mm:ss".

  • Parse time1 and time2 time as string to get the corresponding date objects by using parse() method of the simpleDateFormat class.

  • Calculate the time difference between two date objects in milliseconds by using getTime() method.

  • Now, convert the time difference in milliseconds to hours, minutes and seconds.

  • Print the time difference in screen.

Java Program to Calculate Difference Between Two Time Periods

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDifference {
  public static void main(String[] args) throws Exception {
    String time1 = "02:10:00";
    String time2 = "04:20:00";

    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    // Difference in Milliseconds
    long diffInMs = date2.getTime() - date1.getTime();

    long diffSeconds = diffInMs / 1000 % 60;
    long diffMinutes = diffInMs / (60 * 1000) % 60;
    long diffHours = diffInMs / (60 * 60 * 1000) % 24;

    System.out.format("Difference : %d hours, %d minutes, %d seconds",
            diffHours, diffMinutes, diffSeconds);
  }
}
Output
Difference : 2 hours, 10 minutes, 0 seconds