I have an array of dates, which are currently integers in the format {2010, 5, 13, 2010, 5, 15} and so on. I am trying to use the time.h library to find the difference in days between each date. Here is some code that portrays what is going wrong:
int main()
{
int dates[] = {2010, 4, 14, 2010, 4, 15, 2010, 4, 16};
int* pDates = dates;
printf("%d\n", subtractDates(1, pDates));
return 0;
}
int subtractDates(int i, int* pDates)
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
start_date.tm_hour = 0;
start_date.tm_min = 0;
start_date.tm_sec = 0;
start_date.tm_mon = *(pDates+1)-1;
start_date.tm_mday = *(pDates+2);
start_date.tm_year = *(pDates)-1900;
end_date.tm_hour = 0;
end_date.tm_min = 0;
end_date.tm_sec = 0;
end_date.tm_mon = *(pDates+1+i*3)-1;
end_date.tm_mday = *(pDates+2+i*3);
end_date.tm_year = *(pDates+i*3)-1900;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
return difftime(end_time, start_time) / 86400;
}
This code print outs that the difference between the dates provided is 1 day, which is correct. However, if I remove the third date in the array, like below, the printed value becomes 0, which I do not believe is correct.
int main()
{
int dates[] = {2010, 4, 14, 2010, 4, 15};
int* pDates = dates;
printf("%d\n", subtractDates(1, pDates));
return 0;
}
int subtractDates(int i, int* pDates)
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
start_date.tm_hour = 0;
start_date.tm_min = 0;
start_date.tm_sec = 0;
start_date.tm_mon = *(pDates+1)-1;
start_date.tm_mday = *(pDates+2);
start_date.tm_year = *(pDates)-1900;
end_date.tm_hour = 0;
end_date.tm_min = 0;
end_date.tm_sec = 0;
end_date.tm_mon = *(pDates+1+i*3)-1;
end_date.tm_mday = *(pDates+2+i*3);
end_date.tm_year = *(pDates+i*3)-1900;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
return difftime(end_time, start_time) / 86400;
}
I just don't understand why it is returning 0 considering that all I have done is remove three values in the array, and those three values were not even used in the first program. Any help would be appreciated, thanks.
The problem that I was having is that I was assigning and returning doubles as integers. By just making amendments regarding this I was able to get my code to work. Thanks to everyone who helped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.