Calculating the Difference Between Two Time Periods in C++
When working with time-based data in C++, you may need to determine the exact duration between two time values. Whether you're building scheduling features, logging user activity, or tracking time intervals for performance, this calculation plays an important role in many applications.
In this sub-article, we'll show you how to calculate the difference between two time periods in C++ using the time.h
header.
This example continues the logic established in our C language lead article, adapting it to the C++ programming language using modern coding conventions.
Required Header File
To work with time functions, include:
#include <ctime> // for time_t, tm, mktime, difftime
C++ Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in C++ using time.h
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
// Step-1 Declare two time structures
struct tm time1 = {0}, time2 = {0};
// Step-2 Initialize the first time (YYYY-MM-DD HH:MM:SS)
time1.tm_year = 2025 - 1900; // Year since 1900
time1.tm_mon = 4; // May (0-based index)
time1.tm_mday = 1;
time1.tm_hour = 10;
time1.tm_min = 30;
time1.tm_sec = 0;
// Step-3 Initialize the second time
time2.tm_year = 2025 - 1900;
time2.tm_mon = 4;
time2.tm_mday = 9;
time2.tm_hour = 15;
time2.tm_min = 45;
time2.tm_sec = 0;
// Step-4 Convert both structures to time_t (epoch time)
time_t t1 = mktime(&time1);
time_t t2 = mktime(&time2);
// Step-5 Find the difference in seconds
double seconds = difftime(t2, t1);
// Step-6 Convert seconds to hours, minutes, seconds
int hours = seconds / 3600;
int minutes = ((int)seconds % 3600) / 60;
int remainingSeconds = (int)seconds % 60;
// Step-7 Display the result
cout << "\nTIME DIFFERENCE: " << hours << " HOURS, "
<< minutes << " MINUTES, "
<< remainingSeconds << " SECONDS\n";
return 0;
}
Output
TIME DIFFERENCE: 205 HOURS, 15 MINUTES, 0 SECONDS
Explanation
In this C++ example:
-
We used the
tm
structure to represent individual time components. -
The
mktime()
function converts these structures totime_t
format, which is a numeric representation of time. -
The
difftime()
function gives us the difference in seconds between twotime_t
values. -
We then transformed the total seconds into hours, minutes, and seconds for easier readability.
This approach is efficient and portable for basic date and time calculations in C++.