Michi
Michi

Reputation: 5297

Calculate time in C language

I am trying to calculate time in C language and i have the following program:

#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;
}

The program works almost ok:

Output 1:

./program 
Start time (HH:MM): 05:40
End time (HH:MM): 14:00
The difference is 8:20.

Output 2:

./program 
Start time (HH:MM): 14:00
End time (HH:MM): 22:20
The difference is 8:20.

Output 3:

/program 
Start time (HH:MM): 22:20
End time (HH:MM): 05:40
The difference is -16:-40.

As you can see, I got -16:-40 instead of 7:20.

I cannot figure out how to fix this.

Upvotes: 0

Views: 237

Answers (1)

Clifford
Clifford

Reputation: 93466

If end is after midnight and start before, add 24 hours to the end value:

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

Note too that all the code related to mktime and tm struct is unnecessary. Those are useful when you require time normalisation (for example if you set tm_hour to 25, mktime will generate a time_t value that is 0100hrs the following day, rolling over the month and year too if necessary), but here you are dealing with just time of day in hours and minutes, so you need just:

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

Upvotes: 1

Related Questions