Print difference of two times in hours, minutes and seconds in c language.
This code snippet will print the difference of two times in hours, minutes and seconds. This program will read two times in HH:MM:SS using structure and calculate difference of entered times.
C Code Snippet - Print difference of two times in HH:MM:SS
/*Print difference of two times in hours, minutes and seconds in c language.*/
#include <stdio.h>
struct time{
int hour, minute, second;
};
int main(){
time t1, t2, t3;
int seconds1, seconds2, totalSeconds;
printf("Enter first time in HH:MM:SS : ");
scanf("%d:%d:%d",&t1.hour, &t1.minute, &t1.second);
printf("Enter second time in HH:MM:SS: ");
scanf("%d:%d:%d",&t2.hour, &t2.minute, &t2.second);
//calculate difference
//get time in total seconds
seconds1 = t1.hour*60*60 + t1.minute*60 + t1.second;
seconds2 = t2.hour*60*60 + t2.minute*60 + t2.second;
totalSeconds = seconds1-seconds2;
//extract time in Hours, Minutes and Seconds
t3.minute = totalSeconds/60;
t3.hour = t3.minute/60;
t3.minute = t3.minute%60;
t3.second = totalSeconds%60;
printf("Time difference is: %02d:%02d:%02d\n", t3.hour, t3.minute, t3.second);
}
Enter first time in HH:MM:SS : 12:50:50
Enter second time in HH:MM:SS: 10:30:20
Time difference is: 02:20:30