-
Date calculation program
Hi there,
The programe below outputs the difference between two dates, i want to edit it so the 1st date is always today's date. Would i need to use the time function or rawtime. I am struggling to integrate it into the format of this programme. Could anyone point me in the right direction?
Code:
#include <stdio.h> //
#include <time.h> // Include C time functions in header
int daysto(struct tm *before, struct tm *after) // Grouping code for daysto calculation
{
time_t first = mktime(before), second = mktime(after); // Declaring time_t
if ( first != (time_t)-1 && second != (time_t)-1 ) // If first and second date is not equal return the difference
{
return difftime(second, first) / (60 * 60 * 24); // Converting time into days. difftime function for first and second date
}
return-1 ; //Anything non zero is true
}
int main(void) // Function takes no arguements
{
struct tm one = {0}, two = {0};
one.tm_year = 109; // mktime function caclculates from the year 1900
one.tm_mon = 3 - 1; // Month input. Months start a 0 so -1
one.tm_mday = 24; // Day of the month input
two.tm_year = 109; // mktime function calculates from the year 1900
two.tm_mon = 4 - 1; // Month input. Months start a 0 so -1
two.tm_mday = 3; // Day of the month input
printf("Number of days till deadline = %d\n", daysto(&one,&two)); // Printing the result of the calculation
return 0;
}
Thanks in advance
-
The function time() will give you current time() in the same format as mktime() gives you.
--
Mats
-
Sorry to bring this up again so long after I posted, but i am still struggling with this problem. I have tried to include time() into the code, but I'm not sure how I should edit this part of the code:
Code:
one.tm_year = 109; // mktime function caclculates from the year 1900
one.tm_mon = 3 - 1; // Month input. Months start a 0 so -1
one.tm_mday = 24; // Day of the month input
This is the bit which i want to always be todays date. Would i just leave each one as 'one.tm_mon' or do i need some kind of variable for each part?
Sorry if this is a stupid question, just can't get my head around it!
-
Code:
time_t t;
struct tm one;
time(&t);
one = *localtime(&t);
// If needed, set hours, minutes and seconds to zero.
Sorry all, I'm giving away fish here ;)
--
Mats
-
ahh it works! thank you :)
-
You do what you gotta do, Mats. ;)
It's great watching you land 'em!