
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Calculate Difference Between Two Time Period
There are two time periods provided in the form of hours, minutes and seconds. Then their difference is calculated. For example:
Time period 1 = 8:6:2 Time period 2 = 3:9:3 Time Difference is 4:56:59
C++ Program to Find Difference Between Two Times
To find the time differences then check whether we need to borrow time, for example, adding 60 seconds if the second time has more seconds. Then just subtract the hours, minutes, and seconds of the second time from the first time to get the result.
Example
In this example, you will see the time difference of two different times.
#include <iostream> using namespace std; int main() { int hour1 = 5, minute1 = 45, second1 = 30; int hour2 = 2, minute2 = 50, second2 = 40; int diff_hour, diff_minute, diff_second; if (second2 > second1) { minute1--; second1 += 60; } diff_second = second1 - second2; if (minute2 > minute1) { hour1--; minute1 += 60; } diff_minute = minute1 - minute2; diff_hour = hour1 - hour2; cout << "Time Difference is " << diff_hour << ":" << diff_minute << ":" << diff_second; return 0; }
The above program produces the following result:
Time Difference is 2:54:50
Find Difference Between Two Times Using difftime() Function
The difftime() is C++ in-built function which comes under <ctime> header file. It is used to calculate the two different times in second.
Syntax
The basic syntax of difftime() in C++ as follows:
double difftime(time_t end, time_t start);
Here,
- time_t end: The time_t object is used for the end time.
- time_t start: The time_t object is used for the start time.
Example
In this example, we take two fixed times and convert them into total seconds. It then calculates the difference between them and print the result.
#include <iostream> #include <ctime> using namespace std; int main() { // Set two example times: h:m:s int h1 = 2, m1 = 30, s1 = 15; int h2 = 4, m2 = 10, s2 = 45; // Convert both times to total seconds time_t t1 = h1 * 3600 + m1 * 60 + s1; time_t t2 = h2 * 3600 + m2 * 60 + s2; // difftime() to calculate the difference double diff = difftime(t2, t1); cout << "Time difference: " << abs(diff) << " seconds" << endl; return 0; }
The above program produces the following result:
Time difference: 6030 seconds