Calculate Difference between Two Time Periods in Java

Exercise:

Write a Java Program to calculate difference between two time periods.

Click Here to View the Solution!
public class Time{
  
     int sec, min,hour;
  
     public Time(int hour, int min, int sec) {
         this.hour = hour;
         this.min = min;
         this.sec = sec;
     }
      public static void main(String[] args) 
    {
         // create objects of Time class
         Time start = new Time(6, 10, 49);
         Time stop = new Time(11, 45, 13);
         Time diff;
  
         // calls for difference method
         diff = difference(start, stop);
  
         System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hour, start.min, start.sec);
         System.out.printf("%d:%d:%d ", stop.hour, stop.min, stop.sec);
         System.out.printf("= %d:%d:%d\n", diff.hour, diff.min, diff.sec);
     }
      public static Time difference(Time start, Time stop)
     {
         Time diff = new Time(0, 0, 0);
  
      // if start time’s seconds are greater than stopping time
      // then it will convert minutes of stop into seconds and add them to seconds
         // and add seconds to stop second
         if(start.sec > stop.sec){
             --stop.min;
             stop.sec += 60;
         }
  
         diff.sec = stop.sec - start.sec;
  
         // if start minutes are greater than stopping minutes 
         // then it will convert stop hour into minutes and add it to stop minutes
         if(start.min > stop.min){
             --stop.hour;
             stop.min += 60;
         }
  
         diff.min = stop.min - start.min;
         diff.hour = stop.hour - start.hour;
  
         // return the difference time
         return(diff);
     }
 } 
Click Here to View the Output!
TIME DIFFERENCE: 6:10:49 - 11:44:73 = 5:34:24
Click Here to View the Explanation!
  • The given program shows a class called Time which has three data members namely hour, min, and sec. These data members true to their name, represent just the same of a provided time.
  • The constructor of this class ‘Time’ assigns values for these three given data members.
  • For the main functionality of this program which refers to finding out the difference between the two time frames, difference() function is created. It uses mathematical calculations to find out the time difference between the two parameters which it takes and then returns the result as an object of the type Time class.