tags:

views:

722

answers:

3

Hi my first time is 12:10:20 PM and second time is 7:10:20 Am of the same day how can i find diff b/w them??

My idea is convert all the time to seconds and find the difference again convert to time

is it good Approch r anything else??

+12  A: 

You want the difftime function.

Edit

If you don't have difftime available I would suggest just converting from whatever format you're in to seconds from the epoch, do your calculations and covert back to whatever format you need. The following group of functions can help you with all those conversions:

asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, localtime_r - transform date and time to broken-down time or ASCII

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

Robert S. Barnes
Keep in mind this is for C99 only.
paxdiablo
Would you happen to know how widely supported C99 is? I know it's still not completely supported gcc according to spec yet, but I would think that 10 years later it would be mostly supported in most systems ( wishful thinking on my part? )
Robert S. Barnes
+4  A: 

Not necessarily the best way, but if you wish to use what's available on the system, difftime() and mktime() can 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 );
Hexagon
Information Helpful
Cute
A: 

Your approach sounds sensible.

Taking it one stage further, you could conver to a universal time format, such as Unix time, and then take the difference.

Steve Melnikoff