ADVERTISEMENT
ADVERTISEMENT

Print difference of two times in hours, minutes and seconds in c language.


IncludeHelp 21 June 2016

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

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.