C Program to Calculate Difference Between Two Time Periods

1. Introduction

Calculating the difference between two time periods is a common task in various applications. In this tutorial, we'll demonstrate how to compute the difference between two given time periods using structures in C.

2. Program Overview

1. Define a structure named Time to store hours, minutes, and seconds.

2. Declare two instances of this structure for two time periods.

3. Ask the user to input both time periods.

4. Calculate the difference between these two time periods.

5. Display the difference.

3. Code Program

#include <stdio.h>

// Structure to represent time
struct Time {
    int hours;
    int minutes;
    int seconds;

int main() {
    struct Time start, stop, diff;

    // Input time period 1
    printf("Enter start time (hh:mm:ss): ");
    scanf("%d:%d:%d", &start.hours, &start.minutes, &start.seconds);

    // Input time period 2
    printf("Enter stop time (hh:mm:ss): ");
    scanf("%d:%d:%d", &stop.hours, &stop.minutes, &stop.seconds);

    // Calculate time difference
    while (stop.seconds < start.seconds) {
        stop.seconds += 60;
    diff.seconds = stop.seconds - start.seconds;

    while (stop.minutes < start.minutes) {
        stop.minutes += 60;
    diff.minutes = stop.minutes - start.minutes;

    diff.hours = stop.hours - start.hours;

    // Display the difference
    printf("\nTIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds);
    printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds);
    printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

    return 0;


Enter start time (hh:mm:ss): 8:15:30
Enter stop time (hh:mm:ss): 12:45:50

TIME DIFFERENCE: 8:15:30 - 12:45:50 = 4:30:20

4. Step By Step Explanation

1. A struct named Time is defined to represent time, containing integers for hours, minutes, and seconds.

2. Two instances of this structure, start and stop, are declared to store the two time periods. Another instance diff is declared to store their difference.

3. The user is prompted to input both the start and stop times.

4. The program then calculates the difference between these times. While calculating the difference, it adjusts for overflows in seconds and minutes (e.g., if the seconds of the start time is greater than the stop time, it borrows one minute from the minutes and adds 60 to the seconds).

5. Finally, the difference is displayed to the user.