C Program to Calculate Difference Between Two Time Periods

In this example, you’ll learn to calculate the difference between two time periods using user defined – differenceBetweenTimePeriod function.

Example: Calculate Difference Between Two Time Periods

1. #include <stdio.h>
2. struct TIME
3. {
4. int seconds;
5. int minutes;
6. int hours;
7. };
8. void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff);
9. int main()
10. {
11. struct TIME startTime, stopTime, diff;
12. printf("Enter start time: \n");
13. printf("Enter hours, minutes and seconds respectively: ");
14. scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds);
15. printf("Enter stop time: \n");
16. printf("Enter hours, minutes and seconds respectively: ");
17. scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds);
18. // Calculate the difference between the start and stop time period.
19. differenceBetweenTimePeriod(startTime, stopTime, &diff);
20. printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds);
21. printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds);
22. printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);
23. return 0;
24. }
25. void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff)
26. {
27. if(stop.seconds > start.seconds){
28. --start.minutes;
29. start.seconds += 60;
30. }
31. diff->seconds = start.seconds - stop.seconds;
32. if(stop.minutes > start.minutes){
33. --start.hours;
34. start.minutes += 60;
35. }
36. diff->minutes = start.minutes - stop.minutes;
37. diff->hours = start.hours - stop.hours;
38. }

Output

Enter start time:
Enter hours, minutes and seconds respectively: 12
34
55
Enter stop time:
Enter hours, minutes and seconds respectively:8
12
15

TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40

In this program, user is asked to enter two time periods and these two periods are stored in structure variables startTime and stopTime respectively.

Then, the function differenceBetweenTimePeriod calculates the difference between the time periods and the result is displayed in main() function without returning it (Using call by reference technique).