C++ Program to Calculate Difference Between Two Time Periods Using Structure

In this C++ program, we will find the difference between two time periods using a user defined structure. A time period is uniquely defined as triplets of hours, minutes and seconds.
For Example : 2 hour 20 minutes and 10 seconds.

Points to remember about Structures in C++
  • Keyword struct is used to declare a structure.
  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

To store a time period we will define a user defined structure "Time" having three member variables hour, mins and secs.

struct Time {
  int hour;
  int mins;
  int secs;
};

We will use variables of structure Time, to time periods.


C++ Program to Calculate Difference Between Two Time Periods

// C++ program to find difference between two time periods
#include <iostream>
using namespace std;

struct Time {
  int hour;
  int mins;
  int secs;
};

Time findTimeDifference(Time t1, Time t2);

int main() {
    Time t1, t2, diff;
    
    cout << "Enter earlier time in hours, minutes and seconds\n";
    cin >> t1.hour >> t1.mins >> t1.secs;

    cout << "Enter current time in hours, minutes and seconds\n";
    cin >> t2.hour >> t2.mins >> t2.secs;
    
    diff = findTimeDifference(t1, t2);

    cout << "Difference = "<< diff.hour << ":" << diff.mins << ":" << diff.secs;
    return 0;
}

Time findTimeDifference(Time t1, Time t2){
 Time diff;
    if(t2.secs > t1.secs){
        --t1.mins;
        t1.secs += 60;
    }

    diff.secs = t1.secs - t2.secs;
    if(t2.mins > t1.mins) {
        --t1.hour;
        t1.mins += 60;
    }
    
    diff.mins = t1.mins-t2.mins;
    diff.hour = t1.hour-t2.hour;
    
    return diff;
}
Output
Enter earlier time in hours, minutes and seconds
5 15 40
Enter current time in hours, minutes and seconds
2 40 14
Difference = 2:35:26

In this program, we take two Time periods as input from user in the form of hours, minutes and seconds and store in structure variable t1 and t2. To find the difference between t1 and t2, we call "findTimeDifference" function by passing t1 and t2. Finally, we display the difference of time periods in screen using cout.