English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C Program to Calculate the Difference Between Two Time Periods

Comprehensive Collection of C Programming Examples

In this example, you will learn to use user-defined functions to calculate the difference between two time periods.

To understand this example, you should understand the followingC Programming LanguageTopic:

Calculate the difference between two time periods

#include <stdio.h>
struct TIME {
   int seconds;
   int minutes;
   int hours;
};
void differenceBetweenTimePeriod(struct TIME t1,
                                 struct TIME t2,
                                 struct TIME *diff);
int main() {
   struct TIME startTime, stopTime, diff;
   printf("Enter start time. 
");
   printf("Enter hours, minutes, and seconds: ");
   scanf("%d %d %d", &startTime.hours,
         &startTime.minutes,
         &startTime.seconds);
   printf("Enter stop time. 
");
   printf("Enter hours, minutes, and seconds: ");
   scanf("%d %d %d", &stopTime.hours,
         &stopTime.minutes,
         &stopTime.seconds);
   //Time difference between start and stop times
   differenceBetweenTimePeriod(startTime, stopTime, &diff);
   printf("\nTime difference: %d:%d:%d - ", startTime.hours,
          startTime.minutes,
          startTime.seconds);
   printf("%d:%d:%d ", stopTime.hours,
          stopTime.minutes,
          stopTime.seconds);
   printf("= %d:%d:%d\n", diff.hours,
          diff.minutes,
          diff.seconds);
   return 0;
}
//Calculate the difference between time periods
void differenceBetweenTimePeriod(struct TIME start,
                                 struct TIME stop,
                                 struct TIME *diff) {
   while (stop.seconds > start.seconds) {
      --start.minutes;
      start.seconds += 60;
   }
   diff->seconds = start.seconds - stop.seconds;
   while (stop.minutes > start.minutes) {
      --start.hours;
      start.minutes += 60;
   }
   diff->minutes = start.minutes - stop.minutes;
   diff->hours = start.hours - stop.hours;
}

Output result

Enter start time.
Enter hours, minutes, and seconds: 12
34
55
Enter stop time.
Enter hours, minutes, and seconds: 8
12
15
Time difference: 12:34:55 - 8:12:15 = 4:22:40

In this program, the user is required to input two time periods and these periods are stored separately in structure variables startTime and stopTime.

Then, the function differenceBetweenTimePeriod() calculates the difference between time periods. It displays the result from the main() function without returning it (usingReference CallingTechnology).

Comprehensive Collection of C Programming Examples