Calculate time to some date

Hello!
I need to find how many days, hours and minutes remain to some specific date and I wonder why the following program shows incorrect values, such as 4 days 23 hours etc to 14:00 this Saturday from 17:33 today...

#include <stdio.h>
#include <time.h>

int main()
{
    time_t elaps, timettx, curtime;
    struct tm *elaps_st, time_x;

    time_x.tm_year = 2009-1900;
    time_x.tm_mon = 6;
    time_x.tm_mday = 11;
    time_x.tm_hour = 14;
    time_x.tm_min = 0;
    time_x.tm_sec = 0;
    time_x.tm_isdst = 1;

    time(&curtime);
    printf("Current time:   %s", ctime(&curtime));
    timettx = mktime(&time_x);
    printf("Time X:         %s", ctime(&timettx));
    elaps = timettx - curtime;
    printf("Diff time:      %s", ctime(&elaps));
    elaps_st = localtime(&elaps);

    printf("To time X remain %d days %d hours %d min %d sec\n", elaps_st->tm_mday, elaps_st->tm_hour, elaps_st->tm_min, elaps_st->tm_sec);
}

Using function ctime here is wrong as it gives the elapsed time in secs. from the epoch...just divide the elapsed time "elaps" by the number of hours in a day to give the days left until Sat 14:00. Do same to get hrs/mins/secs until Sat 14:00...

d = elaps / (60*60*24);
h = (elaps - (d * 60*60*24)) / (3600);
printf("%d days %d hrs left\n", d, h);

shamrock
Thanks a lot! I've implemented all my stuff with your code! But as you can see, I use localtime() function. Could you kindly explain, why localtime() finction here does not convert seconds to tm struct correctly?.. As I know, all unix time is just amount of seconds from 1 Jan 1970, so when I have some rather small value in seconds, why localtime() put incorrect amount of days, hours etc in tm struct?..

That's because the "elaps_st = localtime(&elaps);" command gets the date and time stamp that is "elaps" seconds from the epoch...which is very different from how many days hours minutes and seconds separate two dates. Post the output of the program you wrote as it will be easier to explain in relation to that.

  1. call strptime() to convert a date into a struct tm.
  2. get current epoch seconds using time(),
    (if the second "date" is not today, then use
    #1 and #3 to get another time_t value in seconds.)
  3. call strftime() with format %s on the struct from #1.
  4. you now have two time_t values in seconds.

With modulo arutmetic and subtraction - 86400 seconds per day, 3600 seconds per hour, 60 seconds per minute. You now have the number of days hours, etc between two times.