我正在尝试用 C 语言计算时间,我有以下程序:
#include <stdio.h>
#include <time.h>
int main(void) {
int hours, minutes;
double diff;
time_t end, start;
struct tm times;
times.tm_sec = 0;
times.tm_min = 0;
times.tm_hour = 0;
times.tm_mday = 1;
times.tm_mon = 0;
times.tm_year = 70;
times.tm_wday = 4;
times.tm_yday = 0;
time_t ltt;
time(<t);
struct tm *ptm = localtime(<t);
times.tm_isdst = ptm->tm_isdst;
printf("Start time (HH:MM): ");
if((scanf("%d:%d", ×.tm_hour, ×.tm_min)) != 2){
return 1;
}
start = mktime(×);
printf("End time (HH:MM): ");
if((scanf("%d:%d", ×.tm_hour, ×.tm_min)) != 2){
return 1;
}
end = mktime(×);
diff = difftime(end, start);
hours = (int) diff / 3600;
minutes = (int) diff % 3600 / 60;
printf("The difference is %d:%d.\n", hours, minutes);
return 0;
}
程序几乎可以正常运行:
输出1:
./program Start time (HH:MM): 05:40 End time (HH:MM): 14:00 The difference is 8:20.
输出2:
./program Start time (HH:MM): 14:00 End time (HH:MM): 22:20 The difference is 8:20.
输出3:
/program Start time (HH:MM): 22:20 End time (HH:MM): 05:40 The difference is -16:-40.
如您所见,我得到的是 -16:-40 而不是 7:20。
我不知道如何解决这个问题。
最佳答案
如果 end
在午夜之后且 start
在午夜之前,则在 end
值上加上 24 小时:
if( end < start )
{
end += 24 * 60 * 60 ;
}
diff = difftime(end, start);
还要注意,所有与 mktime 和 tm 结构相关的代码都是不必要的。当您需要时间标准化时,这些很有用(例如,如果您将 tm_hour 设置为 25,mktime 将生成第二天的 0100 小时的 time_t 值,如有必要,也会滚动月份和年份),但是在这里,您只处理一天中的时间(以小时和分钟为单位),因此您只需要:
int hour ;
int minute ;
if((scanf("%d:%d", &hour, &minute)) != 2){
return 1;
}
start = (time_t)((hour * 60 + minute) * 60) ;
printf("End time (HH:MM): ");
if((scanf("%d:%d", &hour, &minute)) != 2){
return 1;
}
end = (time_t)((hour * 60 + minute) * 60) ;
关于C语言计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929870/