Google News
logo
C++ Program to Calculate Difference Between Two Time Period
In the following example of C++ program to calculate the difference between two time periods :
Program :
#include <iostream>
using namespace std;

struct Time {
   int hours;
   int minutes;
   int seconds;
};

void difference(Time t1, Time t2, Time *diff);

int main() {
   Time t1, t2, diff;

   cout << "Enter start time." << endl;
   cout << "Hours: ";    cin >> t1.hours;
   cout << "Minutes: ";  cin >> t1.minutes;
   cout << "Seconds: ";  cin >> t1.seconds;

   cout << endl << "Enter end time." << endl;
   cout << "Hours: ";    cin >> t2.hours;
   cout << "Minutes: ";  cin >> t2.minutes;
   cout << "Seconds: ";  cin >> t2.seconds;

   difference(t1, t2, &diff);

   cout << endl << "Time difference: " << diff.hours << " hours, "
        << diff.minutes << " minutes, " << diff.seconds << " seconds.";

   return 0;
}

void difference(Time t1, Time t2, Time *diff) {
   if (t2.seconds > t1.seconds) {
      --t1.minutes;
      t1.seconds += 60;
   }

   diff->seconds = t1.seconds - t2.seconds;

   if (t2.minutes > t1.minutes) {
      --t1.hours;
      t1.minutes += 60;
   }

   diff->minutes = t1.minutes - t2.minutes;
   diff->hours = t1.hours - t2.hours;
}
Output :
Enter start time.
Hours: 03
Minutes: 16
Seconds: 51
Enter end time.
Hours: 09
Minutes: 38
Seconds: 12
Time difference: -7 hours, 38 minutes, 39 seconds.
* In this program, we first define a Time structure to hold the hours, minutes, and seconds of a time period.

* We then prompt the user to enter the start and end times, and read the inputs into two Time structures t1 and t2.

* Next, we call the difference() function, passing in the two time periods and a pointer to a third Time structure diff.

* The difference() function calculates the time difference between t1 and t2 and stores the result in diff. It first checks if the seconds of t2 are greater than those of t1, and adjusts the minutes accordingly. It then calculates the difference in minutes and hours, taking care to adjust for the possibility of negative values.

* Finally, we display the time difference in hours, minutes, and seconds using cout.