我是一名初学者,我试图计算两个日期之间的天数,但我不清楚时间。我可以指出我的错误吗?因为打印后sec = 0。谢谢。
#include <stdio.h>
#include <time.h>
main(){
double sec;
struct tm BD;
BD.tm_mday;
BD.tm_mon;
BD.tm_year;
struct tm KT;
KT.tm_mday;
KT.tm_mon;
KT.tm_year;
printf("Start date: ");
scanf("%d %d %d",&BD.tm_mday,&BD.tm_mon,&BD.tm_year);
printf("End date: ");
scanf("%d %d %d",&KT.tm_mday,&KT.tm_mon,&KT.tm_year);
sec = difftime(mktime(&KT),mktime(&BD));
printf("%f",sec);
// date= sec/86400 //
return 0;
}
答案 0 :(得分:1)
请尝试这个例子。您需要将时钟设置为午夜并将结果舍入为整数,然后计算是正确的:
#include <stdio.h>
#include <time.h>
int main () {
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double seconds;
printf("Start date: ");
scanf("%d %d %d",&start_date.tm_mday ,&start_date.tm_mon,&start_date.tm_year);
printf("End date: ");
scanf("%d %d %d",&end_date.tm_mday,&end_date.tm_mon,&end_date.tm_year);
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
seconds = difftime(end_time, start_time);
printf ("%d days difference\n", (int) (0.5 + seconds/(60*60*24)));
return 0;
}
测试
Start date: 23 11 2017
End date: 27 11 2017
4 days difference
答案 1 :(得分:0)
在调用mktime()
之前,代码无法设置所需的字段。结果:未定义的行为。
struct tm BD;
// these 3 lines of code do nothing
BD.tm_mday;
BD.tm_mon;
BD.tm_year;
scanf("%d %d %d",&BD.tm_mday,&BD.tm_mon,&BD.tm_year);
// Only 3 of the 9+ fields of `BD` have a defined value.
首先将结构归零并设置tm_isdst
。要正确使用mktime()
,除了tm_yday
和tm_wday
之外,所有字段都需要先设置。这两个字段因阅读而被忽略。所有字段都更新为其主要范围。
由于struct tm
可能包含超过定义的9个字段集,因此很容易将整个结构的字段初始化为零,以确保所有字段都已设置。编码器经常忘记设置tm_isdst
和其他可选字段,导致结果不一致。
#include <stdio.h>
#include <time.h>
int main(void) {
struct tm BD = { 0 };
// Set to -1 to direct mktime() to decide if DST applies or not.
// or set to 0, or 1, if a specific DST flag is desired.
BD.tm_isdst = -1;
struct tm KT = { 0 };
KT.tm_isdst = -1;
printf("Start date: ");
if (3 != scanf("%d %d %d", &BD.tm_mday, &BD.tm_mon, &BD.tm_year)) return -1;
printf("End date: ");
if (3 != scanf("%d %d %d", &KT.tm_mday, &KT.tm_mon, &KT.tm_year)) return -1;
double sec = difftime(mktime(&KT), mktime(&BD));
printf("%f\n", sec);
return 0;
}