# C++ program to calculate the difference between two time periods

In this tutorial, we’ll learn how to calculate the difference between two given time periods in C++. The time periods should be provided by the user. The user can provide two time periods. It should be in the form of hours, minutes and seconds.

To understand this example we need to have vast knowledge in C++ topics such as Structures, Functions and Pointers. Kindly find the links mentioned below on the topics Structures, Functions and Pointers attached for better understand.

Consider an example, as it would be helpful further.

Time period 1 = 9 : 6 : 2

Time period 2 = 5 : 9 : 3

The Time difference = 3 : 56 : 59

## Difference between the two time periods using C++

• In the below program, the user will be giving the two time periods in the form of hours, minutes and seconds such that the structure variable stores t1 and t2 respectively.
• TimeDifference() function can be used to find the difference between the time periods.
• Finally, the output screen will display the time period difference from the main() function without returning to it ( call by reference).

Also, refer to the following topics for better understand:
Structures in C++
Functions in C++
Pointers in C++

Program:

```#include <iostream>
using namespace std;

struct TIME_PERIOD
{
int sec;
int min;
int hours;
};

void TimeDifference(struct TIME_PERIOD, struct TIME_PERIOD, struct TIME_PERIOD *);

int main()
{
struct TIME_PERIOD t1, t2, difference;
cout << "Enter the Time Period 1." << endl;
cout << "Enter hours, minutes and seconds of Time Period 1: ";
cin >> t1.hours >> t1.min >> t1.sec;

cout << "Enter the Time Period 2." << endl;
cout << "Enter hours, minutes and seconds of Time Period 2: ";
cin >> t2.hours >> t2.min >> t2.sec;

TimeDifference(t1, t2, &difference);

cout << endl << "The Time Period difference is: " << t1.hours << ":" << t1.min << ":" << t1.sec;
cout << " - " << t2.hours << ":" << t2.min << ":" << t2.sec;
cout << " = " << difference.hours << ":" << difference.min << ":" << difference.sec;
return 0;
}
void TimeDifference(struct TIME_PERIOD t1, struct TIME_PERIOD t2, struct TIME_PERIOD *difference)
{

if(t2.sec > t1.sec)
{
--t1.min;
t1.sec += 60;
}

difference->sec = t1.sec - t2.sec;
if(t2.min > t1.min)
{
--t1.hours;
t1.min += 60;
}
difference->min = t1.min-t2.min;
difference->hours = t1.hours-t2.hours;
}```

Output:

```Enter the Time Period 1.

Enter hours, minutes and seconds of Time Period 1: 12 45 35

Enter the Time Period 2.

Enter hours, minutes and seconds of Time Period 1: 6 21 23

The Time Period difference is: 12:45:35 - 6:21:23 = 6:24:12```