我有一组日期,目前是{2010,5,13,2010,5,15}格式的整数,依此类推。我正在尝试使用time.h库来查找每个日期之间的天数差异。以下是一些描述出错的代码:
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;
}
此代码打印出所提供日期之间的差异为1天,这是正确的。但是,如果我删除数组中的第三个日期,如下所示,打印值将变为0,我认为这是不正确的。
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;
}
我只是不明白为什么它会返回0,因为我所做的就是删除数组中的三个值,而这三个值甚至没有在第一个程序中使用。任何帮助将不胜感激,谢谢。
答案 0 :(得分:0)
我遇到的问题是我正在分配并返回双精度作为整数。通过对此进行修改,我能够使我的代码工作。感谢所有帮助过的人。