Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the difference between two times in c?

Tags:

c++

c

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??

like image 808
Cute Avatar asked Dec 02 '22 07:12

Cute


2 Answers

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 )

like image 184
Robert S. Barnes Avatar answered Dec 04 '22 22:12

Robert S. Barnes


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 );
like image 21
Hexagon Avatar answered Dec 04 '22 22:12

Hexagon