用C语言计算时间

时间:2015-08-10 21:57:33

标签: c

我正在尝试用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(&ltt);

    struct tm *ptm = localtime(&ltt);
    times.tm_isdst = ptm->tm_isdst;

    printf("Start time (HH:MM): ");

    if((scanf("%d:%d", &times.tm_hour, &times.tm_min)) != 2){
        return 1;
    }

    start = mktime(&times);
    printf("End time (HH:MM): ");

    if((scanf("%d:%d", &times.tm_hour, &times.tm_min)) != 2){
        return 1;
    }
    end = mktime(&times);

    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。

我无法弄清楚如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

如果end在午夜之后且start之前,请将{24}小时添加到end值:

if( end < start )
{
    end += 24 * 60 * 60 ;
}
diff = difftime(end, start);

另请注意,与mktime和tm结构相关的所有代码都是不必要的。当您需要时间标准化时,这些非常有用(例如,如果将tm_hour设置为25,则mktime将生成time_t值,该值在第二天为0100hrs,如果需要也会在月份和年份滚动),但是在这里,您只需要处理小时和分钟中的时间,所以您只需要:

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) ;