1. ## Time difference

I have read in a time in the format HH:MM:SS from a file into a string variable.

The problem i have is i need to subtract the times from each other to find the difference.

Is there such a thing as a time variable which allows subtraction, or is there another way to do this?

Thanks guys.

2. You can use the time() & localtime() functions

Code:
```struct tm * curtime;
time_t bintime;

time(&bintime);
curtime = localtime(&bintime);```

3. Thanks for the reply, unfortunately i'm unsure how to use this to solve my problem.

Say i have 2 times:
12:34:50
12:34:46

how could i use the time function to subtract these and get an answer of 4. Remembering that i am storing the time in a character array.

4. Code:
```char tm1 = "12:34:50", tm2 = "12:34:46";
int iDiff(0);

tm1[2]=tm1[5]=tm2[2]=tm2[5]=0;
iDiff = (atoi(tm1)-atoi(tm2))*3600 + (atoi(tm1+3)-atoi(tm2+3))*60 + (atoi(tm1+6)-atoi(tm2+6));	// Calculate difference in seconds```

5. I just wrote it down quickly, i didn't have the time to test it..
It's ment to be a pointer to how it can be done

6. thanks for your help, it doesn't give the correct answer but i get the jist.

am i right in thinking that

tm1[2]=tm1[5]=tm2[2]=tm2[5]=0;

shoulde be
tm1[2]=tm1[5]=tm2[2]=tm2[5]= '0';

now to work on the equation.

Thanks again

7. No, setting them to 0 terminates the string at that position. Setting it to '0', only pads the string with '0'

printf(tm); // Displays hours
printf(tm+3); // Displays minutes
printf(tm+6); // Displays seconds

8. ok sorry, i get it now. It works great.

>Salem - how did you mean the algorithm is broken, it works fine for me.

I have:

Code:
```                char tm1[9] = "12:34:50";
char tm2[9] = "12:35:46";
int iDiff = 0 ;

tm1[2]=tm1[5]=tm2[2]=tm2[5]=0;

iDiff = (atoi(tm1)-atoi(tm2))*3600 + (atoi(tm1+3)-atoi(tm2+3))*60 + (atoi(tm1+6)-atoi(tm2+6));

cout << iDiff ;```

9. Knutso, your algorithm won't work if its a single-digit hour.

Try this:
Code:
```#include <iostream>
#include <cstdio>

int main( void ) {

char tm1[] = "12:34:50";
char tm2[] = "12:34:46";

int h1, m1, s1;
int h2, m2, s2;

sscanf( tm1, "%d:%d:%d", &h1, &m1, &s1 );
sscanf( tm2, "%d:%d:%d", &h2, &m2, &s2 );

std::cout<<"Time difference is: "<<( h1 - h2 ) * 3600 + ( m1 - m2 ) * 60 + ( s1 - s2 )<<std::endl;

}```

10. Or you could use something like this to store the times, then use difftime()

Code:
```  struct tm mytmdate;
time_t    tim;
mytmdate.tm_year  = 2003 - 1900;
mytmdate.tm_mon   = 4;
mytmdate.tm_mday  = 1;
mytmdate.tm_hour  = 20;
mytmdate.tm_min   = 10;
mytmdate.tm_sec   = 0;
mytmdate.tm_isdst = -1;
tim = mktime(&mytmdate);
printf("Time is %s\n", ctime (&tim));```