How to find the difference between two times in c?

my first time is 12:10:20 PM and the second time is 7:10:20 in the morning of the same day, how can I find diff b / w them ??

My idea converts all the time in seconds and again finds the difference in the return time

Is it anything else good?

+4
source share
3 answers

Not necessarily the best way, but if you want to use what is available on the system, difftime () and mktime () may help -

#include <time.h> tm Time1 = { 0 }; // Make sure everything is initialized to start with. /* 12:10:20 */ Time1.tm_hour = 12; Time1.tm_min = 10; Time1.tm_sec = 20; /* Give the function a sane date to work with (01/01/2000, here). */ Time1.tm_mday = 1; Time1.tm_mon = 0; Time1.tm_year = 100; tm Time2 = Time1; // Base Time2 on Time1, to get the same date... /* 07:10:20 */ Time2.tm_hour = 7; Time2.tm_min = 10; Time2.tm_sec = 20; /* Convert to time_t. */ time_t TimeT1 = mktime( &Time1 ); time_t TimeT2 = mktime( &Time2 ); /* Use difftime() to find the difference, in seconds. */ double Diff = difftime( TimeT1, TimeT2 ); 
+7
source

You need a difftime function.

Edit

If you do not have difftime available, I would suggest simply converting from any format you are in, seconds from the era, to perform your calculations and hide back to whatever format you need. The following group of functions can help you with all these conversions:

asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, localtime_r - convert date and time to decay mode or ASCII

timegm, timelocal - reverse to gmtime and localtime (may not be available for all systems)

+12
source

Your approach sounds reasonable.

Following another step, you can move on to a universal time format, such as Unix time , and then accept the difference.

0
source

All Articles