# Convert time difference into seconds?

• 08-13-2011
Convert time difference into seconds?
I am writing an alarm clock program. Basically, it takes a time from the user and converts the difference between that time and the current into seconds. However, this function only returns the number of seconds the user gives. That is to say, it never seems to execute the if statements.
I.E. -
Code:

```Enter the hour- 12 Enter the minute- 00 Enter the seconds- 00 Sat Aug 13 12:00:00 2011 Total number of seconds = 0 This is the current time ===> Sat Aug 13 11:58:19 2011```
There is probably a better way to achieve the time difference conversion; I would be open to suggestions.

Code:

```int TimeDifference(time_t time, time_t now) {         int Hour, Min;         long int Sec;         struct tm *currentTime;         currentTime = localtime (&now);         struct tm *timeinfo;         timeinfo = localtime (&time);         Sec = timeinfo->tm_sec;         if (currentTime->tm_min != timeinfo->tm_min)         {         Min = (timeinfo->tm_min - currentTime->tm_min);         Sec += (Min * 60);         }         if (currentTime->tm_hour != timeinfo->tm_hour)         {         Hour = (timeinfo->tm_hour - currentTime->tm_hour);         Sec += (Hour * 60 * 60);        //to minutes then to seconds         }         printf("Total number of seconds = %li", Sec);         return Sec; }```
• 08-13-2011
Prelude
Quote:

There is probably a better way to achieve the time difference conversion; I would be open to suggestions.
Code:

```int TimeDifference(time_t time, time_t now) {     return (int)difftime(now, time); }```
;)
• 08-13-2011
tabstop
Prelude's answer is the way to go, on the assumption you've filled a time_t with the user info. You might have gotten a hint if you had checked "currentTime==timeinfo"; my man page says
Quote:

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.
and yours very well may too.
• 08-13-2011