Link to home
Start Free TrialLog in
Avatar of MarioC82
MarioC82Flag for Cyprus

asked on

finding difference between two datetime values in C

Hi,

I have the following problem. I have to find the elapsed time in seconds between two given dates in the following format.

yyyyMMddhhmmss example: 20101118190541

Now i have two of these as a char [14] array and i need to find the difference in seconds between them.

Is there any C library which is portable or some algorithm i can use to calculate it ?
Avatar of Infinity08
Infinity08
Flag of Belgium image

You can easily calculate the difference between two timestamps in time_t format using difftime :

        http://www.cplusplus.com/reference/clibrary/ctime/difftime/

It's just a matter of getting the corresponding time_t for your timestamp. And that can be done by parsing the timestamp, filling a struct tm, and then calling mktime :

        http://www.cplusplus.com/reference/clibrary/ctime/mktime/
Avatar of MarioC82

ASKER

I will have a look at this and respond again.
Hi i have a quick question, with the above date format would something like this work to populate the tm struct.

fromDate is a char[14] array containing the date.

scanf(fromDate, "%.4s%.2s%.2s%.2s%.2%.2", t->tm_year, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_wday);

However i dont seem to get the values to pass i only get current date still.
You are missing %s in sscanf
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Infinity08.