Originally Posted by
IndioDoido
hey Dave!
yap, it's not that complex, as i said before :P sorry...
Good, then hopefully this won't be either. This is just my concept of your problem. I hope the comments are actually useful to you.
Code:
#include <stdio.h>
#include <time.h>
int main(void)
{
char buffer[BUFSIZ];
double diff;
time_t begin, end, now;
struct tm *local, stop, start = {0};
/*
* Obtain start date. Here I'll fake it (May 10, 2007).
*/
start.tm_year = 2007 - 1900;
start.tm_mon = 5 - 1;
start.tm_mday = 10;
/*
* Make this into a "real" time.
*/
begin = mktime(&start);
if ( begin == (time_t)-1 )
{
return 0;
}
/*
* Then localize it.
*/
local = localtime(&begin);
if ( !local )
{
return 0;
}
start = *local; /* start is now normalized and localized */
/*
* This far we've just been dealing with the start date. The normalization
* and localization is to get things in their proper ranges and such. That
* is, no such thing as May 119th, for example.
*
* Now we get to pretty much repeat the process with the end date.
*/
stop = start; /* a copy of the start */
stop.tm_mday += 30; /* add 30 days */
/*
* Now normalize the end date.
*/
end = mktime(&stop);
if ( end == (time_t)-1 )
{
return 0;
}
/*
* And let's find out the current date and time.
*/
now = time(NULL);
if ( now == (time_t)-1 )
{
return 0;
}
/*
* All righty, let's find out how much time in seconds is between now and
* the end.
*/
diff = difftime(end, now);
/*
* Then convert seconds into days, and then lop off the fraction.
*/
diff /= 60 * 60 * 24;
diff = (int)diff;
printf("diff = %g\n", diff); /* only for demonstration purposes, remove */
/*
* But let's dress this up a bit. Let's localize the end.
*/
local = localtime(&end);
if ( !local )
{
return 0;
}
/*
* And bear with me, let's localize the current time as well.
*/
local = localtime(&now);
if ( !local )
{
return 0;
}
/*
* Now we can use strftime on both the start and the end to make nice
* messages.
*/
strftime(buffer, sizeof buffer, "%A %B %d, %Y", &start);
printf("Your subscription began %s\n", buffer);
strftime(buffer, sizeof buffer, "%A %B %d, %Y", &stop);
printf("Your subscription will end %s\n", buffer);
strftime(buffer, sizeof buffer, "%A %B %d, %Y", local);
printf("Today is %s. You have %g days remaining.\n", buffer, diff);
/*
* And we're done!
*/
return 0;
}
/* my output
diff = 17
Your subscription began Thursday May 10, 2007
Your subscription will end Saturday June 09, 2007
Today is Tuesday May 22, 2007. You have 17 days remaining.
*/
There's just a kind of general pattern of back-and-forth between struct tm's and timet_t's. Other than that tediousness, it's not as bad as it looks. While not terribly simple to understand at first, working with date and time using the standard library isn't that tough. (Other than being tough to look at.)
I think now you ought to be able to put together the code you are trying to develop. Post your latest attempts if you still have questions.