Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

difftime — C23 time function

`difftime(time1, time0)` from `<time.h>` computes `time1 - time0` for two `time_t` calendar times and returns the difference in seconds as `double`. It is the portable interface because the encoding of `time_t` is unspecified.

Version: C23

Syntax

double difftime(time_t time1, time_t time0);

difftime(time1, time0) from <time.h> computes time1 - time0 for two time_t calendar times and returns the difference in seconds as double. It is the portable interface because the encoding of time_t is unspecified.

The example creates two local calendar times 90 seconds apart with mktime and calls difftime in both directions. Output 90 -90 demonstrates the argument order and the sign of the returned difference.

Do not subtract time_t values directly on the assumption that they count seconds. First check that time-producing functions did not return (time_t)-1; over very large spans, double might not represent every individual second exactly, so do not assume an integral result.

Examples

#include <stdio.h>
#include <time.h>

int main(void) {
    struct tm first = {.tm_year = 124, .tm_mon = 0, .tm_mday = 1, .tm_hour = 12, .tm_isdst = -1};
    struct tm second = first;
    second.tm_min = 1;
    second.tm_sec = 30;
    time_t start = mktime(&first);
    time_t finish = mktime(&second);
    if (start == (time_t)-1 || finish == (time_t)-1) return 1;
    printf("%.0f %.0f\n", difftime(finish, start), difftime(start, finish));
    return 0;
}

Result

90 -90

The example creates two local calendar times 90 seconds apart with `mktime` and calls `difftime` in both directions. Output `90 -90` demonstrates the argument order and the sign of the returned difference.

Sources