首页 > 解决方案 > Difftime 给出的值大于预期值

问题描述

当我打印 difftime 的结果时,我得到结果:-4334284568731237.000000。为什么是这样?

    //time1 and time2 are both of type time_t

    time_t temp;

    char val[] = "06:02";
    struct tm tm;
    strptime(val, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time1 = temp;

    char val2[] = "06:43";
    struct tm tm;
    strptime(val2, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time2 = temp;

    printf("%f\n", difftime(items[0].time1, items[0].time2));

标签: ctime

解决方案


我假设tm变量是在块范围内声明的,具有自动存储持续时间。

为什么是这样?

您只需设置小时和分钟:

struct tm tm;                  // uninitialized
strptime(val2, "%H:%M", &tm);  // sets only tm.tm_hour and tm.tm_min

strptime不初始化tm,只存储它读取的内容。的其余成员struct tm未初始化,因此它们具有“不确定”值 - 任何值。因此,第tm一个年份的值可能与另一个年份不同,这可能会导致解析时返回tm的内容有很大差异。mktimetm

strptime手册页:tm should be initialized before the call。所以在调用之前初始化结构strptime

struct tm tm = {0};
strptime(val2, "%H:%M", &tm);

推荐阅读