Difference between two given time periods in C++

Given two time periods in HH:MM:SS format where HH represents hours, MM represents minutes, and SS represents seconds, find the difference between them in the same format. The approach uses borrowing (similar to subtraction in arithmetic) when seconds or minutes of the smaller time are greater.

Worked Example

Time period 1 = 8:06:02
Time period 2 = 3:09:03

Step 1: Seconds: 02 < 03, borrow 1 minute ? 62 - 03 = 59 seconds
Step 2: Minutes: 05 < 09, borrow 1 hour  ? 65 - 09 = 56 minutes
Step 3: Hours:   7 - 3 = 4 hours

Time Difference = 4:56:59

C++ Implementation

The following program calculates the difference between two time periods using hardcoded values (no user input needed) ?

#include <iostream>
using namespace std;

int main() {
    int hour1 = 8, minute1 = 6, second1 = 2;
    int hour2 = 3, minute2 = 9, second2 = 3;
    int diff_hour, diff_minute, diff_second;

    cout << "Time 1: " << hour1 << ":" << minute1 << ":" << second1 << endl;
    cout << "Time 2: " << hour2 << ":" << minute2 << ":" << second2 << endl;

    // Borrow from minutes if seconds need it
    if (second2 > second1) {
        minute1--;
        second1 += 60;
    }
    diff_second = second1 - second2;

    // Borrow from hours if minutes need it
    if (minute2 > minute1) {
        hour1--;
        minute1 += 60;
    }
    diff_minute = minute1 - minute2;

    diff_hour = hour1 - hour2;

    cout << "Time Difference: " << diff_hour << ":"
         << diff_minute << ":" << diff_second << endl;

    return 0;
}

The output of the above code is ?

Time 1: 8:6:2
Time 2: 3:9:3
Time Difference: 4:56:59

Conclusion

The time difference is calculated by subtracting seconds, minutes, and hours separately, borrowing from the next larger unit when needed (similar to manual subtraction). This approach assumes Time 1 is always greater than Time 2.

Updated on: 2026-03-14T13:00:31+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements