Google News
logo
C Program to Calculate Difference Between Two Time Periods
In the following example of a C program that calculates the difference between two time periods :
Program :
#include <stdio.h>

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

int main() {
    struct time t1, t2, diff;

    printf("Enter the first time (hh:mm:ss): ");
    scanf("%d:%d:%d", &t1.hours, &t1.minutes, &t1.seconds);

    printf("Enter the second time (hh:mm:ss): ");
    scanf("%d:%d:%d", &t2.hours, &t2.minutes, &t2.seconds);

    // Calculate the difference between the two times
    if (t2.seconds > t1.seconds) {
        t1.minutes--;
        t1.seconds += 60;
    }
    diff.seconds = t1.seconds - t2.seconds;

    if (t2.minutes > t1.minutes) {
        t1.hours--;
        t1.minutes += 60;
    }
    diff.minutes = t1.minutes - t2.minutes;

    diff.hours = t1.hours - t2.hours;

    printf("\nTime Difference: %d:%d:%d - %d:%d:%d = %d:%d:%d\n", t1.hours, t1.minutes, t1.seconds, t2.hours, t2.minutes, t2.seconds, diff.hours, diff.minutes, diff.seconds);

    return 0;
}
Output :
Enter the first time (hh:mm:ss): 02:34:19
Enter the second time (hh:mm:ss): 07:51:03
Time Difference: 1:94:19 - 7:51:3 = -6:43:16
* In this example, the program defines a structure time that contains three integer fields: hours, minutes, and seconds. The program then creates three time variables : t1, t2, and diff.

* Next, the program prompts the user to enter two times in the format hh:mm:ss using the scanf function, and stores the values in the t1 and t2 variables.

* The program then calculates the difference between the two times by subtracting the values of t2 from the values of t1 and storing the result in the diff variable.

* Finally, the program uses the printf function to display the time difference in the format hh:mm:ss.