Diffrence between time HH:MM:SS

PHOTO EMBED

Tue Aug 27 2024 17:00:11 GMT+0000 (Coordinated Universal Time)

Saved by @Xyfer #c++

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

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

// Function to calculate time difference
Time calculateTimeDifference(Time t1, Time t2) {
    Time difference;

    // Calculate total seconds for both times
    int seconds1 = t1.hours * 3600 + t1.minutes * 60 + t1.seconds;
    int seconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;

    // Difference in seconds
    int diffSeconds = seconds1 - seconds2;

    // Convert difference back to hours, minutes, seconds
    difference.hours = diffSeconds / 3600;
    diffSeconds = diffSeconds % 3600;
    difference.minutes = diffSeconds / 60;
    difference.seconds = diffSeconds % 60;

    return difference;
}

int main() {
    // Input the two times
    Time t1, t2;
    char colon;
    cin >> t1.hours >> colon >> t1.minutes >> colon >> t1.seconds;
    cin >> t2.hours >> colon >> t2.minutes >> colon >> t2.seconds;

    // Calculate the difference
    Time difference = calculateTimeDifference(t1, t2);

    // Output the difference in HH:MM:SS format
    cout << setfill('0') << setw(2) << difference.hours << ":"
         << setfill('0') << setw(2) << difference.minutes << ":"
         << setfill('0') << setw(2) << difference.seconds << endl;

    return 0;
}
content_copyCOPY