C语言计算时间

标签 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。

我不知道如何解决这个问题。

最佳答案

如果 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/

相关文章:

清除终端程序 Linux C/C++ 的输出

c - 调用者和被调用者的参数怎么可能不同?

c - `int const a[5]` 到底是什么意思?

c - 如何在C代码中使用SFTP访问特定目录

c - 如何从递归函数内部写入文件

c - OpenGl部署: Running it on other peoples computers?

c - 在文件的字符数组中搜索 2 个连续的十六进制值

c++ - 变量 + 值宏扩展

c - 在 C 中打印 IP 版本和 IP header

C 结构体和函数指针